简体   繁体   中英

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. I just know how to create a udp socket, I am not sure how to proceed. 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?

You would do this with the bind() function:

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. 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:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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