From owner-freebsd-net Tue Jul 9 17: 5:58 2002 Delivered-To: freebsd-net@freebsd.org Received: from mx1.FreeBSD.org (mx1.FreeBSD.org [216.136.204.125]) by hub.freebsd.org (Postfix) with ESMTP id 7436237B400 for ; Tue, 9 Jul 2002 17:05:54 -0700 (PDT) Received: from gw.catspoiler.org (217-ip-163.nccn.net [209.79.217.163]) by mx1.FreeBSD.org (Postfix) with ESMTP id DF65643E4A for ; Tue, 9 Jul 2002 17:05:53 -0700 (PDT) (envelope-from dl-freebsd@catspoiler.org) Received: from mousie.catspoiler.org (mousie.catspoiler.org [192.168.101.2]) by gw.catspoiler.org (8.12.5/8.12.5) with ESMTP id g6A05Wwr005505; Tue, 9 Jul 2002 17:05:36 -0700 (PDT) (envelope-from dl-freebsd@catspoiler.org) Message-Id: <200207100005.g6A05Wwr005505@gw.catspoiler.org> Date: Tue, 9 Jul 2002 17:05:32 -0700 (PDT) From: Don Lewis Subject: Re: Bind to specific address on FreeBSD To: term@velocitus.net Cc: freebsd-net@FreeBSD.ORG In-Reply-To: MIME-Version: 1.0 Content-Type: TEXT/plain; charset=us-ascii Sender: owner-freebsd-net@FreeBSD.ORG Precedence: bulk List-ID: List-Archive: (Web Archive) List-Help: (List Instructions) List-Subscribe: List-Unsubscribe: X-Loop: FreeBSD.org On 9 Jul, Chris Given wrote: > I can't figure out why this code won't bind to 127.0.0.1 on FreeBSD. I get > an error "Can't assign requested address". > > struct sockaddr_in dp; > unsigned long bind_to_addr = inet_addr("127.0.0.1"); > > sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); > if(sock < 0) { > printf("Error socket : %s\n", strerror(errno)); > return -1; > } > > dp.sin_family = AF_INET; > dp.sin_addr.s_addr = htonl(bind_to_addr); > dp.sin_port = htons(1234); In addition to the byte order problem you haven't initialized the sin_len member of dp and cleared the sin_zero member. Typically code will zero out the entire structure to clear any padding or fields that can default to zero before it stores the desired data in the structure. Here's an example I found in rwhod: struct sockaddr_in sin; ... memset(&sin, 0, sizeof(sin)); sin.sin_len = sizeof(sin); sin.sin_family = AF_INET; sin.sin_port = sp->s_port; if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) { syslog(LOG_ERR, "bind: %m"); exit(1); } To Unsubscribe: send mail to majordomo@FreeBSD.org with "unsubscribe freebsd-net" in the body of the message