Date: Wed, 10 Jul 2002 11:23:26 -0500 From: "Matthew Finlay" <matt@omegaband.com> To: "Chris Given" <term@velocitus.net>, <freebsd-net@freebsd.org> Subject: Re: Bind to specific address on FreeBSD Message-ID: <011001c2282e$1e5fd9c0$ad96a8c0@seagullsemi.com> References: <B6C2B288BB8D5542AA2485606CD47462125366@exchange.rmci.net>
next in thread | previous in thread | raw e-mail | index | archive | help
first zero out your sockaddr_in structure before using it.
bzero(&dp, sizeof(dp));
and then be sure and set the len field in sockaddr_in struct;
dp.sin_len = sizeof(dp);
also... get rid of the htonl(bind_to_addr) because inet_addr puts the
address in network byte order.
i compiled with those changes and the bind succeeded. my guess is the
sockaddr_in struct had garbage in the fields that werent initialized...
causing an error somewhere along the way.
-matt
----- Original Message -----
From: "Chris Given" <term@velocitus.net>
To: <freebsd-net@freebsd.org>
Sent: Tuesday, July 09, 2002 4:50 PM
Subject: Bind to specific address on FreeBSD
> 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".
>
> #include <stdio.h>
> #include <sys/types.h>
> #include <sys/time.h>
> #include <time.h>
> #include <sys/socket.h>
> #include <netinet/in.h>
> #include <netdb.h>
> #include <errno.h>
> #include <stdio.h>
> #include <string.h>
> #include <arpa/inet.h>
> #include <unistd.h>
> #include <stdlib.h>
>
> int main() {
> int sock;
> 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);
>
> if(bind(sock, (struct sockaddr*)&dp, sizeof(struct sockaddr_in))!=0)
> {
> printf("Bind failed : %s\n", strerror(errno));
> } else {
> printf("Bind success\n");
> }
> }
>
> To Unsubscribe: send mail to majordomo@FreeBSD.org
> with "unsubscribe freebsd-net" in the body of the message
>
To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-net" in the body of the message
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?011001c2282e$1e5fd9c0$ad96a8c0>
