Title: Sockets Programming in Linux
1Sockets Programming in Linux
- References
- Internetworking with TCP/IP Vol III - Linux
version - UNIX Network Programming - W. Richard Stevens
2Sockets Programming in Linux
- Linux / UNIX Socket API functions
- Example TCP / UDP Clients
- Example TCP / UDP Servers
3Basic Socket FunctionsServer(Linux / UNIX)
- Create a socket of a particular type
- retcode socket (family, type, protocol )
- s socket (PF_INET, SOCK_STREAM, 0)
- returns socket number or -1 on error
- Bind that socket to a specific port
- retcode bind (socket, localaddr, addrlen )
- n bind (s, (struct sockaddr )myaddr,
sizeof(myaddr)) - returns 0 on success, -1 on fail
4Basic Socket FunctionsServer(Linux / UNIX)
- Wait for an incoming message
- retcode listen (socket, queuelen)
- ans listen(s, 0) / queuelen max 5/
- return value 0 success, -1 fail
- Create a new socket and return new socket ID to
client - retcode accept (socket, addr, addrlen)
- ans accept (s, (struct sockaddr )cl_addr,
sizeof(cl_addr)) - return value socket number success, -1 fail
5Basic Socket Functions Server (Linux / UNIX)
- Read / send a message
- retcode read write (socket, buff, bufflen)
- ans read (s, buf, sizeof(buf))
- ans write (s, buf, sizeof(buf))
- return value word count success, -1 fail
- retcode recv send (socket, buff, bufflen, 0)
- ans recv (s, buf, sizeof(buf), 0)
- ans send (s, buf, sizeof(buf), 0)
- return value word count success, -1 fail
- Close the socket
- retcode shutdown (socket , direction)
- direction 0 means input, 1 means output, 2 means
both - retcode close (socket )
- return value 0 success, -1 fail
6Basic Socket FunctionsClient (Linux / UNIX)
- Create a socket of a particular type
- Socket ( )
- Establish a connection to a remote Port/Socket
- retcode connect (socket, addr, addrlen)
- ans connect (s, (struct sockaddr )svr,
sizeof(svr)) - return value 0 success, -1 fail
- Send and receive messages to/from remote socket
- Read( ) / Write( ) of recv( ) / send(
- Close the socket
- Close ( )
7Additional Socket Functions(Linux / UNIX)
- Byte ordering functions
- servaddr.sin_port htons (SERV_PORT)
- myaddr.sin_addr.s_addr htonl (INADDR_ANY)
- Name resolution functions
- host / protocol / service, by name / address /
port - Other Stuff
- zero out memory blocks
- bzero ((char )myaddr, sizeof(myaddr))
- copy memory blocks
- bcopy (hp-gth_addr, (caddr_T)svaddr.sin_addr,
hp-gth_length)
8Example Linux Client
- Develop a set of procedures that can be used by
other programs to implement client / server. - int connectTCP (host, service)
- int connectsock(host, service, tcp)
- identify service, host, port
- get a socket
- connect to service / host / port
- return socket number
9Linux Client - Connectsock.c
- int connectTCP (char host, char service)
-
- return connectsock (host, service, tcp)
-
10Linux Client - Connectsock.c
- include ltsys/types.hgt, ltsys/socket.hgt,
ltnetinet/in.hgt,ltnetdb.hgt - int connectsock (char host, char service, char
protocol) -
- struct hostent phe
- struct servent pse
- struct protoent ppe
- struct sockaddr_in sin
- int s, type
-
11Linux Client - Connectsock.c
- bzero ((char )sin, sizeof (sin))
- sin.sin_family AF_INET
- if (pse getservbyname (service, protocol) )
- sin.sin_port pse -gts_port
- else if ( (sin.sin_port htons((u_short)atoi(serv
ice))) 0) - error_exit (cant get s service\n, service)
- if (phe gethostbyname (host) )
- bcopy(phe-gth_addr, (char )sin.sin_addr,
phe-gth_length) - else if ((sin.sin_addr.s_addr inet_addr(host))
INADDR_NONE) - error_exit (cant get s host\n, host)
12Linux Client - Connectsock.c
- if ( (ppe getprotobyname (protocol) 0)
- error_exit (cant get s host\n, host)
- if (strcmp (protocol, tcp) 0)
- type SOCK_STREAM
- else type SOCK_DGRAM
- if (s socket (PF_INET, type, ppe-gtp_proto)) lt
0) - error_exit (Cant create a socket\n)
- if (connect (s, (struct sockaddr )sin,
sizeof(sin)) lt 0) - error_exit (cant connect to remote socket\n)
- return s
13Example Linux Client - TCPecho.c
- include ltstdio.hgt
- define LINELEN 128
- int main (argc, argv)
-
- host argv1
- service argv2
- TCPecho (host, service)
- exit (0)
-
14Example Linux Client - TCPecho.c
- int TCPecho (char host, char service)
-
- char bufLINELEN1
- int s, n, outchars, inchars
- s connectTCP (host, service)
- while (fgets (buf, sizeof(buf), stdin))
-
- bufLINELEN \0
- outchars strlen(buf)
- (void) write (s, buf, outchars)
-
15Example Linux Client - TCPecho.c
- for (inchars 0 inchars lt outchars inchars
n) -
- n read (s, bufinchars, outchars -
inchars) - if (n lt 0)
- error_exit(socket read failed\n)
-
- fputs (buf, stdout)
-
-
16TCP Client Algorithm Issues
- Client / Server Communications
- request / response interaction
- write / read (send / recv)
- Single write may require multiple reads
- response may be segmented
- continue appending reads until return length 0
17Example Linux Client - UDPecho.c
- include ltstdio.hgt
- define LINELEN 128
- int main (argc, argv)
-
- host argv1
- service argv2
- UDPecho (host, service)
- exit (0)
-
18Example Linux Client - UDPecho.c
- int UDPecho (char host, char service)
-
- char bufLINELEN1
- int s, n, outchars, inchars
- s connectUDP (host, service)
- while (fgets (buf, sizeof(buf), stdin))
-
- bufLINELEN \0
- outchars strlen(buf)
- (void) write (s, buf, outchars)
19Example Linux Client - UDPecho.c
- if (read (s, buf, nchars) lt 0)
- error_exit (Socket read failed \n)
- fputs (buf, stdout)
-
20Iterative Connectionless ServerTIME Server
- / UDPtimed.c - main /
- include ltsys/types.hgt
- include ltsys/socket.hgt
- include ltnetinet/in.hgt
- include ltstdio.hgt
- include lttime.hgt
- include ltstring.hgt
- extern int errno
- int passiveUDP(const char service)
- int errexit(const char format, ...)
- define UNIXEPOCH 2208988800 / UNIX epoch, in
secs/
21Iterative Connectionless ServerTIME Server
- int main(int argc, char argv)
- struct sockaddr_in fsin / the address of a
client / - char service "time" / service name or port
number / - char buf1 / "input" buffer any size gt 0
/ - int sock / server socket /
- time_t now / current time /
- int alen / from-address length /
- switch (argc)
- case 1 break
- case 2 service argv1
- break
- default errexit("usage UDPtimed port\n")
-
22Iterative Connectionless ServerTIME Server
- sock passiveUDP(service)
- while (1)
- alen sizeof(fsin)
- if (recvfrom(sock, buf, sizeof(buf), 0,
- (struct sockaddr )fsin, alen) lt 0)
- errexit("recvfrom s\n", strerror(errno))
- (void) time(now)
- now htonl((u_long)(now UNIXEPOCH))
- (void) sendto(sock, (char )now, sizeof(now),
0, - (struct sockaddr )fsin, sizeof(fsin))
-
23Concurrent Connection-OrientedTCPechod.c
- include ltsys/types.h, ltsys/signal.h,
ltsys/socket.h, ltsys/time.h, ltsys/resource.h,
ltsys/wait.h, ltsys/errno.h, ltnetinet/in.hgt,
ltpthread.hgt, ltunistd.hgt, ltstdlib.hgt, ltstdio.hgt,
ltstring.hgt, lterrno.hgt - define QLEN 10 / max connect queue
length/ - define BUFSIZE 4096
- extern int errno
- void TCPechod(void pfd)
- int errexit(const char format, ...)
- int passiveTCP(const char service, int qlen)
24Concurrent Connection-OrientedTCPechod.c
- int main(int argc, char argv)
- char service "echo" / service name/port
/ - struct sockaddr_in fsin / address of
client/ - unsigned int alen / len of client addr/
- int msock / master server socket /
- int ssock / slave server socket /
- pthread_t tid
- switch (argc)
- case 1 break
- case 2 service argv1
- break
- default errexit("usage TCPechod
port\n") -
25Concurrent Connection-OrientedTCPechod.c
- msock passiveTCP(service, QLEN)
- while (1)
- alen sizeof(fsin)
- ssock accept (msock, (struct sockaddr
)fsin, alen) - if (ssock lt 0)
- errexit("accept s\n", strerror(errno))
-
- //Now create a thread to handle client request
- pthread_create (tid, NULL, TCPechod, (void
)ssock) - //end of while
- //end of main
26Concurrent Connection-OrientedTCPechod.c
- msock passiveTCP(service, QLEN)
- while (1)
- alen sizeof(fsin)
- ssock accept(msock, (struct sockaddr )fsin,
alen) - if (ssock lt 0)
- errexit("accept s\n", strerror(errno))
-
- //Now create a thread to handle client request
- pthread_create (tid, NULL, TCPechod, (void
)ssock) - //end of while
- //end of main
27Concurrent Connection-OrientedTCPechod.c
- void TCPechod(void pfd)
- char bufBUFSIZE
- int cc, fd
- fd (int ) pfd
- while (cc recv(fd, buf, sizeof (buf), 0))
- if (cc lt 0)
- errexit("echo read s\n", strerror(errno))
- printf ("We got s\n", buf)
- if (send(fd, buf, cc, 0) lt 0)
- errexit("echo write s\n", strerror(errno))
- bzero (buf, sizeof(buf))
-
28Summary
- Sockets API almost identical in Windows and Linux
- Linux does not use WSAStartup, WSACleanup
- Linux uses close(socket), Windows uses
closesocket() - Some differences in Operating System functions
- Multiple threads
- Windows - _beginthread ()
- Linux pthread_create ()
- Multiple Processes
- Windows CreateProcess()
- Linux Fork()