Skip to content

Instantly share code, notes, and snippets.

@seliopou
Last active May 26, 2017 03:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seliopou/06c1258c17e2a8287eef15ffda76109a to your computer and use it in GitHub Desktop.
Save seliopou/06c1258c17e2a8287eef15ffda76109a to your computer and use it in GitHub Desktop.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#define BAIL(ret, msg) do { if ((ret) < 0) { perror(msg); exit(1); } } while (0)
int main() {
int i, fd, ret;
struct sockaddr_in addr_in, addr_out;
socklen_t len;
for (i = 0; i < 10; i++) {
memset(&addr_in, 0, sizeof(addr_in));
memset(&addr_out, 0, sizeof(addr_out));
addr_in.sin_family = AF_INET;
addr_in.sin_port = 0;
addr_in.sin_addr.s_addr = inet_addr("127.0.0.1");
fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
BAIL(fd, "unable to create socket");
ret = bind(fd, (struct sockaddr *)&addr_in, sizeof(addr_in));
BAIL(ret, "unable to bind socket");
len = sizeof(addr_out);
ret = getsockname(fd, (struct sockaddr *)&addr_out, &len);
assert(len == sizeof(addr_out));
BAIL(ret, "getsockname failed");
ret = close(fd);
BAIL(ret, "close failed");
printf("fd %2d, port %d\n", fd, addr_out.sin_port);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment