How to give to a client specific ip address in C

前端 未结 2 1247
不知归路
不知归路 2020-12-15 12:06

I am trying to implement a simple client and server in C and I can\'t find online an example how to set a specific IP address to the client. This is what I got so far:

2条回答
  •  既然无缘
    2020-12-15 12:21

    If you want your client to connect using a specific network interface (say, because you have multiple network cards), then you first need to call bind(2) on that interface's IP address before connecting. For example, if you have two network interfaces with IP addresses 192.168.1.100 and 10.101.151.100, then to connect using the 192.168.1.100 address you could do this:

    // Error checking omitted for expository purposes
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    
    // Bind to a specific network interface (and optionally a specific local port)
    struct sockaddr_in localaddr;
    localaddr.sin_family = AF_INET;
    localaddr.sin_addr.s_addr = inet_addr("192.168.1.100");
    localaddr.sin_port = 0;  // Any local port will do
    bind(sockfd, (struct sockaddr *)&localaddr, sizeof(localaddr));
    
    // Connect to the remote server
    struct sockaddr_in remoteaddr;
    remoteaddr.sin_family = AF_INET;
    remoteaddr.sin_addr.s_addr = inet_addr(server_ip);
    remoteaddr.sin_port = htons(server_port);
    connect(sockfd, (struct sockaddr *)&remoteaddr, sizeof(remoteaddr));
    

提交回复
热议问题