- int sock = -1;
- int retry_cnt = 0;
-
- retry:
- sock = socket(AF_INET, SOCK_DGRAM, 0);
- if (sock < 0) {
- xlog(L_ERROR, "Failed to create RPC socket: %m");
- exit(1);
- }
- fcntl(sock, F_SETFL, O_NONBLOCK);
-
- memset(&address, 0, sizeof(address));
- local_addr->sa_family = AF_INET; /* Default to IPv4 */
-
- /* Bind source IP if provided on command line */
- if (opt_srcaddr) {
- struct addrinfo *ai = smn_lookup(opt_srcaddr);
- if (!ai) {
- xlog(L_ERROR,
- "Not a valid hostname or address: \"%s\"",
- opt_srcaddr);
- exit(1);
- }
-
- /* We know it's IPv4 at this point */
- memcpy(local_addr, ai->ai_addr, ai->ai_addrlen);
-
- freeaddrinfo(ai);
- }
-
- /* Use source port if provided on the command line,
- * otherwise use bindresvport */
- if (opt_srcport) {
- smn_set_port(local_addr, opt_srcport);
- if (bind(sock, local_addr, sizeof(struct sockaddr_in)) < 0) {
- xlog(L_ERROR, "Failed to bind RPC socket: %m");
- exit(1);
- }
- } else {
- struct servent *se;
- struct sockaddr_in *sin = (struct sockaddr_in *)local_addr;
- (void) bindresvport(sock, sin);
- /* try to avoid known ports */
- se = getservbyport(sin->sin_port, "udp");
- if (se && retry_cnt < 100) {
- retry_cnt++;
- close(sock);
- goto retry;
- }
- }