Return to BSD News archive
#! rnews 3014 bsd Path: euryale.cc.adfa.oz.au!newshost.carno.net.au!harbinger.cc.monash.edu.au!news.cs.su.oz.au!metro!metro!munnari.OZ.AU!spool.mu.edu!newspump.sol.net!howland.erols.net!newsfeed.internetmci.com!news.wco.com!news From: "Jeffery T. White" <zellion@cyberwind.com> Newsgroups: comp.unix.bsd.freebsd.misc Subject: Re: How to open a socket under FreeBSD? Date: 27 Oct 1996 15:18:34 GMT Organization: CyberWind Lines: 82 Message-ID: <01bbc41b$ab78c380$df6d04c7@zellion.cyberwind.com> References: <GORSKI.96Oct26172702@axiom.www.xxx> NNTP-Posting-Host: zellion.cyberwind.com X-Newsreader: Microsoft Internet News 4.70.1155 > I want to open a socket under FreeBSD, but all the examples I've found for BSD > use the 'struct sockaddr_in'. FreeBSD needs 'struct sockaddr'! I'm not familiar > with sockets. How can I open a socket under FreeBSD? .... del .... The sockaddr_in struct is a same storage size but more specific version of sockaddr. The "_in" being the INET specific struct members. All of the socket functions are prototyped to take a generic socket. Use sockaddr_in and cast to sockaddr as required. My ?understanding? is that this was done to allow sockets to support multiple protocols without having to change the sockets calls... > None working example (from PSD:20): > ---------------------------------------------------------------------------- ---- > #include <sys/types.h> > #include <sys/socket.h> > #include <netinet/in.h> > #include <stdio.h> > > /* > * In the included file <netinet/in.h> a sockaddr_in is defined as follows: > * struct sockaddr_in { > * short sin_family; > * u_short sin_port; > * struct in_addr sin_addr; > * char sin_zero[8]; > * }; > * > * This program creates a datagram socket, binds a name to it, then reads > * from the socket. > */ > main() > { > int sock, length; > struct sockaddr_in name; > char buf[1024]; > > /* Create socket from which to read. */ > sock = socket(AF_INET, SOCK_DGRAM, 0); > if (sock < 0) { > perror("opening datagram socket"); > exit(1); > } > /* Create name with wildcards. */ > name.sin_family = AF_INET; > name.sin_addr.s_addr = INADDR_ANY; > name.sin_port = 0; > if (bind(sock, &name, sizeof(name))) { if (bind(sock, ( sockaddr * ) &name, sizeof(name))) { > perror("binding datagram socket"); > exit(1); > } > /* Find assigned port value and print it out. */ > length = sizeof(name); > if (getsockname(sock, &name, &length)) { if (getsockname(sock, ( sockaddr * ) &name, &length)) { > perror("getting socket name"); > exit(1); > } > printf("Socket has port #%d\n", ntohs(name.sin_port)); > /* Read from the socket */ > if (read(sock, buf, 1024) < 0) > perror("receiving datagram packet"); > printf("-->%s\n", buf); > close(sock); > } > ---------------------------------------------------------------------------- ---- >