无法连接到vmware vm内的套接字

时间:2014-02-24 23:04:48

标签: c linux sockets network-programming virtual-machine

我在C中创建了一个服务器套接字。这是最简单的TCP服务器示例中最基本的东西。服务器代码如下。我还创建了一个在主机上运行的客户端套接字。代码也在下面。但是,由于某种原因,客户端无法连接到服务器。我使用的IP地址与“ip addr”命令中的条目eth0下的IP地址相同。 VM的网络适配器是桥接连接。

当客户端和服务器在同一台计算机(主机)上运行时,完全相同的代码可以正常工作。

谢谢!

服务器代码:

int sockfd;
int clientfd;
struct sockaddr_in self;
struct sockaddr_in client_addr;
int addrlen = sizeof (client_addr);


if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    perror("Socket");
    return EXIT_FAILURE;
}

printf("Socket descriptor is: %d\n", sockfd);

memset(&self, 0, sizeof (self));
self.sin_family = AF_INET;
self.sin_port = htons(MY_PORT);
self.sin_addr.s_addr = INADDR_ANY;

if (bind(sockfd, (struct sockaddr*) &self, sizeof (self)) != 0) {
    perror("socket--bind");
    return EXIT_FAILURE;
}

if (listen(sockfd, 20) != 0) {
    perror("socket--listen");
    return EXIT_FAILURE;
}

clientfd = accept(sockfd, (struct sockaddr*) &client_addr, &addrlen);
printf("%s:%d connected\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

客户代码:

int sock;
struct sockaddr_in server;
//struct sockaddr_in client; 
struct hostent *hp;
//char buf[BUFFER_SIZE];

if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    die(6, "Opening stream socket");

printf("Client socket file descriptor is: %d\n", sock);

memset(&server, (char) 0, sizeof (server));
server.sin_family = AF_INET;
hp = gethostbyname(host_name);
if (!hp) {
    //sprintf(buf, "%s: unknown host\n", host_name);
    die(8,  "%s: unknown host\n", host_name);
}
memcpy(hp->h_addr, &server.sin_addr, hp->h_length);
server.sin_port = htons((u_short) SERVER_PORT);

/* Try to connect */
if ((connect(sock, (struct sockaddr *) &server, sizeof (server))) < 0)
    die(7, "%s", "Failed to connect stream socket\n");

0 个答案:

没有答案