Sockets - How to find out what port and address I'm assigned

后端 未结 2 1141
死守一世寂寞
死守一世寂寞 2020-12-04 15:39

I\'m having trouble figuring this out - I\'m working with sockets in C using this guide - http://binarii.com/files/papers/c_sockets.txt

I\'m trying to automatically

相关标签:
2条回答
  • 2020-12-04 16:14

    The comment in your code is wrong. INADDR_ANY doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.

    0 讨论(0)
  • 2020-12-04 16:17

    If it's a server socket, you should call listen() on your socket, and then getsockname() to find the port number on which it is listening:

    struct sockaddr_in sin;
    socklen_t len = sizeof(sin);
    if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
        perror("getsockname");
    else
        printf("port number %d\n", ntohs(sin.sin_port));
    

    As for the IP address, if you use INADDR_ANY then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname() on the socket for a specific connection (which you get from accept()) in order to find out which local IP address is being used on that connection.

    0 讨论(0)
提交回复
热议问题