套接字 - 如何找出分配给我的端口和地址 [英] Sockets - How to find out what port and address I'm assigned
问题描述
我无法解决这个问题 - 我正在使用本指南在 C 中使用套接字 - http://binarii.com/files/papers/c_sockets.txt
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
我正在尝试使用以下方法自动获取我的 IP 和端口:
I'm trying to automatically get my ip and port using:
server.sin_port = 0; /* bind() will choose a random port*/
server.sin_addr.s_addr = INADDR_ANY; /* puts server's IP automatically */
...
...
bind(int fd, struct sockaddr *my_addr,int addrlen); // Bind function
绑定成功后,我如何知道我实际分配的 IP 和端口是什么?
After a successful bind, how do I find out what IP and Port I'm actually assigned?
推荐答案
如果是服务器套接字,应该调用 listen()
在您的套接字上,然后 getsockname()
找到它正在监听的端口号:
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
", ntohs(sin.sin_port));
至于 IP 地址,如果您使用 INADDR_ANY
那么服务器套接字可以接受与机器的任何 IP 地址的连接,并且服务器套接字本身没有特定的 IP 地址.例如,如果您的机器有两个 IP 地址,那么您可能会在此服务器套接字上获得两个传入连接,每个连接具有不同的本地 IP 地址.您可以在套接字上使用 getsockname()
进行特定连接(从 accept()
获得),以便找出正在使用的本地 IP 地址连接.
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.
这篇关于套接字 - 如何找出分配给我的端口和地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!