simple tcp socket programming
Roger Oberholtzer
roger
Mon May 17 11:59:43 PDT 2004
On Tue, 24 Feb 2004 22:25:42 +0800
"M.W. Chang" <mwchang at i-cable.com> wrote:
>
> Given this code fragment, how could I modify it to bind to a
> user-specified port, rather than obtaining an available port?
>
> server.c:
>
> /* open socket */
> sock = socket(PF_INET, SOCK_STREAM , 0);
> if (sock < 0) {
> perror("server: Error opening stream socket");
> exit(1);
> }
>
> server.sin_family = PF_INET;
> server.sin_addr.s_addr = INADDR_ANY;
> server.sin_port = 0;
server.sin_port = htons((short) port);
/* Set any socket/protocol options */
int on = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on));
> if (bind(sock, (struct sockaddr *)&server, sizeof server) < 0) {
> perror("server: Error binding server socket to message socket");
> exit(1);
> }
>
> /* obtain the first availble port */
> length = sizeof server;
> if (getsockname(sock, (struct sockaddr *)&server, &length)<0) {
> perror("server: Error obtaining socket name");
> exit(1);
> }
> listen(sock,5);
>
>
> --
> .~. http://toylet.homeip.net
> / v \ Linux 2.4.22-xfs
> /( _ )\ 10:22pm up 1 day 4:27
> ^ ^ load average: 1.00 1.01 1.00
>
> _______________________________________________
> Linux-users mailing list
> Linux-users at smtp.linux-sxs.org
> Unsubscribe/Suspend/Etc ->
> http://smtp.linux-sxs.org/mailman/listinfo/linux-users
>
--
+????????????????????????????+???????????????????????????????+
? Roger Oberholtzer ? E-mail: roger at opq.se ?
? OPQ Systems AB ? WWW: http://www.opq.se/ ?
? Erik Dahlbergsgatan 41-43 ? Phone: Int + 46 8 314223 ?
? 115 34 Stockholm ? Mobile: Int + 46 733 621657 ?
? Sweden ? Fax: Int + 46 8 302602 ?
+????????????????????????????+???????????????????????????????+
More information about the Linux-users
mailing list