我试图让互联网套接字客户端和服务器在同一主机上运行,但我只是从客户端获得连接错误超时连接,我就是这样做的这里的Ubuntu虚拟机是我的代码:
服务器
#include <stdlib.h> /* for getenv */
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> /* Internet domain header */
#include <strings.h>
#define SERVER_PORT 59154
struct sockaddr_in self = {AF_INET};
int main()
{ int soc, ns, k;
char buf[256];
struct sockaddr_in peer = {AF_INET};
int peer_len = sizeof(peer);
char *host;
/* set up listening socket soc */
soc = socket(AF_INET, SOCK_STREAM, 0);
if (soc < 0)
{ perror("server:socket"); exit(1);
}
bzero(&self, sizeof(self));
self.sin_family = AF_INET;
self.sin_addr.s_addr = htonl(INADDR_ANY);
self.sin_port = htons(SERVER_PORT);
if (bind(soc, (struct sockaddr *)&self,
sizeof(self)) == -1)
{ perror("server:bind"); close(soc); exit(1); }
listen(soc, 1);
/* accept connection request */
ns = accept(soc, (struct sockaddr *)&peer, &peer_len);
if (ns < 0)
{ perror("server:accept"); close(soc); exit(1); }
/* data transfer on connected socket ns */
k = read(ns, buf, sizeof(buf));
host = getenv("HOST");
printf("SERVER ON %s RECEIVED: %s\n”,
host, buf);
write(ns, buf, k);
close(ns); close(soc);
return(0);
}
这是客户:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> /* Internet domain header */
#include <netdb.h>
#include <strings.h>
#define SERVER_PORT 59154
struct sockaddr_in peer = {AF_INET};
int main(int argc, char* argv[])
{ int soc;
char buf[256];
struct hostent *hp;
if ( argc != 2 )
{ fprintf(stderr, "Usage: %s hostname\n", argv[0]);
exit(1);
}
/* fill in peer address */
hp = gethostbyname(argv[1]);
if ( hp == NULL )
{ fprintf(stderr, "%s: %s unknow host\n",
argv[0], argv[1]);
exit(1);
}
bzero(&peer, sizeof(peer));
peer.sin_family = AF_INET;
peer.sin_addr.s_addr = htonl(INADDR_ANY);
peer.sin_port = htons(SERVER_PORT);
bcopy(hp->h_addr_list[0],
(char*)&peer.sin_addr, hp->h_length);
/* create socket */
soc = socket(AF_INET, SOCK_STREAM, 0);
/* request connection to server */
if (connect(soc, (struct sockaddr *)&peer,
sizeof(peer)) == -1)
{ perror("client:connect"); close(soc); exit(1); }
write(soc, "Hello Internet", 15);
read(soc, buf, sizeof(buf));
printf("SERVER ECHOED: %s\n", buf);
close(soc); return(0);
}