UNIX Socket Programming
Download
Report
Transcript UNIX Socket Programming
UNIX Socket Programming
CS 6378
Project Reference Book: Unix Network
programming: Networking APIs: Sockets and XTI
(2nd edition), Prentice Hall
>> UNIX System
>> Sockets
>> System Calls
>> TCP Client Server
>> UDP Client Server
>> Threads
User and System
Programs
Kernel Support
Hardware
Socket API
•
Socket API originated with the 4.2 BSD system released in 1983
•
Sockets – A way to speak to other programs using UNIX file
descriptors.
A file descriptor is an integer associated with an open file.This can
be a network connection
Kinds of Sockets-DARPA Internet addresses(Internet Sockets) ,
Unix Sockets, X.25 Sockets etc
Types of Internet Sockets
SOCK_STREAM uses TCP (Transmission Control Protocol)
Connection oriented and Reliable
SOCK_DGRAM uses UDP (User Datagram Protocol)
Connectionless and Unreliable
•
•
•
1.
2.
Structs and Data Handling
•
A socket descriptor is of type int
Byte ordering
Most significant byte first – Network byte order (Big Endian)
Least significant byte first – Host Byte order ( Little ..)
Socket Structures in Network byte order
struct sockaddr { unsigned short sa_family; // address family,
AF_xxx char sa_data[14]; // 14 bytes of protocol address };
struct sockaddr_in { short int sin_family; // Address family
unsigned short int sin_port; // Port number
struct in_addr sin_addr; // Internet address
unsigned char sin_zero[8]; // Same size as struct sockaddr };
Convert the Natives
struct in_addr { unsigned long s_addr; // 32-bit long, or 4 bytes };
If ina is of type struct sockaddr_in
ina.sin_addr.s_addr references the 4-byte IP address (in Network Byte
Order
•
•
•
•
htons() – Host to Network Short
htonl() -- "Host to Network Long"
ntohs() -- "Network to Host Short"
ntohl() -- "Network to Host Long"
IP Addresses
• socket01.utdallas.edu 129.110.43.11
• sol2.utdallas.edu 129.110.34.2 etc
Other UTD machines for use socket02 – socket06 , sol1 , jupiter
Please do not use apache for Network programming
inet_addr() converts an IP address in numbers-and-dots notation into
unsigned long
ina.sin_addr.s_addr = inet_addr(“129.110.43.11”) // Network byte order
Also can use inet_aton() -- “ascii to network”
int inet_aton(const char *cp,struct in_addr *inp);
inet_ntoa returns a string from a struct of type in_addr
inet_ntoa(ina.sin_addr) ;
Useful UNIX Commands
• netstat –i prints information about the interfaces
• netstat –ni prints this information using numeric addresses
• loop back interface is called lo and the ethernet interface is called eth0
or le0 depending on the machine
• netstat –r prints the routing table
• netstat | grep PORT_NO shows the state of the client socket
• ifconfig eth0 – Given the interface name ifconfig gives the details for
each interface --- Ethernet Addr , inet_addr , Bcast , Mask , MTU
• ping IP_addr -- Sends a packet to the host specified by IP_addr and
prints out the roundtrip time ( Uses ICMP messages)
• traceroute IP_addr -- Shows the path from this host to the destination
printing out the roundtrip time for a packet to each hop in between
• Tcpdump communicates directly with Data Link layer UDP Packet fail
System Calls
•
•
•
•
•
•
•
•
•
•
•
•
•
socket() – returns a socket descriptor
int socket(int domain, int type, int protocol);
bind() – What port I am on / what port to attach to
int bind(int sockfd, struct sockaddr *my_addr, int addrlen);
connect() – Connect to a remote host
int connect(int sockfd, struct sockaddr *serv_addr, int addrlen);
listen() – Waiting for someone to connect to my port
int listen(int sockfd, int backlog);
accept() – Get a file descriptor for a incomming connection
int accept(int sockfd, void *addr, int *addrlen);
send() and recv() – Send and receive data over a connection
int send(int sockfd, const void *msg, int len, int flags);
int recv(int sockfd, void *buf, int len, unsigned int flags);
• sendto() and recvfrom() – Send and receive data without connection
• int sendto(int sockfd, const void *msg, int len, unsigned int flags,
const struct sockaddr *to, int tolen);
• int recvfrom(int sockfd, void *buf, int len, unsigned int flags,
struct sockaddr *from, int *fromlen);
• close() and shutdown() – Close a connection Two way / One
way
• getpeername() – Obtain the peer name given the socket file
descriptor
• gethostname() – My computer name
• int sock_get_port(const struct sockaddr *sockaddr,socklen_t
addrlen);
Useful to get the port number given a struct of type sockaddr
Readn() writen() readline() Read / Write a
particular number of bytes
Fork() – To start a new process with
parents addr space
Exec() Load a new program on callers addr
space
Client-Server Programming
• TCP Client Server Example
• Status of client-server before call to accept
• Server
listenfd
●
daytimetcpsrv1.c
Client
● connect()
Status of clientserver after return from accept
listenfd ●
connfd ●
● connect()
Status of Client-Server after fork returns
Server( Parent)
listenfd ●
connfd ●
Server ( Child)
listenfd●
connfd ●
Client
● connect()
Status of Client Server after parent and Child close
appropriate sockets
Server ( Parent)
listenfd ●
Server(Client)
connfd ●
Client
● connect()
Socket functions of UDP Client Server
Socket()
Bind()
Socket()
Sendto()
Recvfrom()
Blocks until datagram
received from a client
recvfrom
Sendto()
Close()
UDP Client
UDP Server
Threads
• Threads are lightweight process which share the process instructions ,
global variables , open files , signal handlers and signal dispositions ,
current working directory and user and group Ids
• Each thread has its own thread ID , set of Registers, PC and Stack
pointer, stack , errno ,signal mask , priority
• Basic Thread Functions : Creation and Termination
• Int pthread_create(pthread_t *tid,const pthread_attr_t *attr,void
*(*func)(void*), void *arg);
• Int pthread_join(pthread_t tid,void **status); // Wait for a thread to
terminate
• pthread_t pthread_self(void); //Returns thread ID of calling thread
• Int pthread_detach(pthread_t pid);//We cannot wait for it to terminate,
On its termination all resources are released
• Void pthread_exit(void *status);
• Threads/tcpserv01.c
Thread Synchronization
• Shared data can be protected using mutex locks provided by the
pthread library
• int pthread_mutex_lock(pthread_mutex_t *mptr);
• int pthread_mutex_unlock(pthread_mutex_t *mptr);
• Threads/example02.c
• Can use condition variables for signalling mechanism
• int pthread_cond_wait(pthread_cond_t *cptr,pthread_mutex_t *mptr);
• int pthread_cond_signal(pthread_cond_t *cptr);
• Can also use System semaphores from <semaphores.h> See manual
~syrotiuk/pthreads.cc
References
• UNIX Network Programming , Networking
APIs: Sockets and XTI : W Richard Stevens
• Beej’s Guide to Network Programming
www.ecst.csuchico.edu/~beej/guide/net/
• Dr Syrotiuk’s web page with sample
networking programs
www.utdallas.edu/~syrotiuk/cs6378/work.html