简体   繁体   English

如何将udp套接字绑定到单个单播地址

[英]how to bind a udp socket to a single unicast address

I dont have any experience in c programming and I am kind of stuck with an assignment where I have to create a udp socket and bind it with a unicast ip address and an ephemeral port. 我没有任何C编程经验,我有点执着于一个任务,我必须创建一个udp套接字并将其与单播ip地址和一个临时端口绑定。 I just know how to create a udp socket, I am not sure how to proceed. 我只知道如何创建udp套接字,我不确定如何继续。 Any help, links will be greatly appreciated. 任何帮助,链接将不胜感激。 Thank you! 谢谢!

I searched the internet and found out we can use the get_ifi_info function to get interface list, but how do we find out which is the unicast ip? 我搜索了互联网,发现可以使用get_ifi_info函数获取接口列表,但是我们如何找出哪个是单播ip?

You would do this with the bind() function: 您可以使用bind()函数执行此操作:

int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

The first parameter is the file descriptor for the socket. 第一个参数是套接字的文件描述符。 The second is a pointer to a socket address structure which contains (for IPv4 or IPv6) the IP address and port to bind to. 第二个是指向套接字地址结构的指针,该结构包含(对于IPv4或IPv6)要绑定到的IP地址和端口。 The third is the size of the structure pointed to by the second parameter. 第三个是第二个参数指向的结构的大小。

For example: 例如:

int s = socket(AF_INET, SOCK_DGRAM, 0); // AF_INET is for IPv4
if (s == -1) {
    perror("socket failed");
    exit(1);
}

struct sockaddr_in sin;  // socket address structure specific to IPv4
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr("192.168.1.2");    // binds to the local address 192.168.1.2
sin.sin_port = 0;    // 0 means the OS picks the port

if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
    perror("bind failed");
    exit(1);
}
printf("bind succeeded\n");

You can then use the getsockname() function if you need to learn which port was actually chosen: 如果需要了解实际选择了哪个端口,则可以使用getsockname()函数:

struct sockaddr_in sin;  // socket address structure specific to IPv4
socklen_t sinlen = sizeof(sin);
memset(&sin, 0, sizeof(sin));

if (getsockname(s, (struct sockaddr *)&sin, &sinlen) == -1) {
    perror("getsockname failed");
    exit(1);
}
printf("bound to port %hu\n", ntohs(sin.sin_port));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM