如何使用套接字在两台机器之间建立连接

时间:2017-10-10 17:15:51

标签: c linux sockets

我想使用C编程的套接字在两个虚拟机之间建立连接。客户端套接字位于Kali linux虚拟机上,服务器套接字位于Windows Server 2008 R2 VM上。虚拟机上的网络适配器设置为NAT。服务器的IP地址是192.168.1.5,客户端的IP地址是192.168.1.3并且有连接,我之间有ping。当客户端和服务器都在linux机器上时,套接字工作正常。但是当我在服务器计算机上创建和启动服务器套接字时,我之间没有连接,我无法从客户端套接字上的服务器获取消息。有人可以帮忙吗?有我的套接字代码:

服务器套接字:

<li  [ngClass]="isLogedIn() ? 'dropdown' : 'hidden_item'">
                    <a  [routerLink]="['Mailbox', {'boxname': 'inbox'}]" class="dropdown-toggle" data-toggle="dropdown">Messages <span class="nav-up-carret"></span></a>
                    <ul class="dropdown-menu" role="menu">
                        <li><a [routerLink]="['Mailbox', {'boxname': 'inbox'}]">Inbox</a> </li>
                        <li><a [routerLink]="['Mailbox', {'boxname': 'sent'}]">Sent</a></li>
                    </ul>
                </li>

客户端套接字:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>


int main() {

    char server_message[256] = "YOU HAVE REACHED THE SERVER";
    int server_socket;
    server_socket = socket(AF_INET, SOCK_STREAM, 0);

    //DEFINE THE SERVER ADDRESS

    struct sockaddr_in server_address;
    server_address.sin_family = AF_INET;
    server_address.sin_port = htons(9002);
    server_address.sin_addr.s_addr = inet_addr("192.168.1.3");

    //BIND SOCKET TO OUR SPECIFIED IP AND PORT

    bind(server_socket, (struct sockaddr*)&server_address, sizeof(server_address));
    listen(server_socket, 5);
    int client_socket;

    client_socket = accept(server_socket, NULL, NULL);

    //SEND THE MESSAGE
    send(client_socket, server_message,sizeof(server_message),0);

    //close the socket

    close(server_socket);

    return 0; 
}

0 个答案:

没有答案