UNIX SOCKET PROGRAMMING
OutlineSocket and Internet SocketsNetwork programming functionsSocket System CallsTCP Sockets ProgrammingUDP Sockets Programming
SocketsSocketsbull Sockets provide mechanisms to communicate
between computers across a network
bull There are different kind of sockets
bullBerkeley sockets is the most popular Internet Socketndash runs on Linux FreeBSD Windows
Network APINetwork APIbull Operating system provides Application
Programming Interface (API) for network application
bull API is defined by a set of function types data structures and constants
bull Application Programming Interface for networks is called socket
Internet SocketsInternet Sockets
bullSupport stream and datagram packets (eg TCP UDP IP)
bullIs Similar to UNIX file IO API
bullBased on C
Types of Internet SocketsTypes of Internet Socketsbull Different types of sockets implement different
communication types (stream vs datagram)bull Type of socket stream socket
ndash connection-orientedndash two way communicationndash reliable (error free) in order deliveryndash can use the Transmission Control Protocol
(TCP)ndash eg telnet http
bull Type of socket datagram socketndash connectionless does not maintain an open
connection each packet is independentndash can use the User Datagram Protocol (UDP)ndash eg IP telephony
Data typesData types
int8_t signed 8bit intuint8_t unsigned 8 bit intint16_t signed 16 bit intuint16_t unsigned 16 bit intint32_t signed 32 bit intuint32_t unsigned 32 bit int
u_char u_short u_int u_long
More data typesMore data typessa_family_t address familysocklen_t length of structin_addr_t IPv4 addressin_port_t IP port number
Naming and AddressingNaming and Addressingbull Host name
ndash identifies a single host ndashvariable length string (eg
wwwberkeleyedu)ndash is mapped to one or more IP addresses
bull IP Addressndashwritten as dotted octets (eg 10001)ndash32 bits Not a number But often needs to
be converted to a 32-bit to usebull Port number
ndash identifies a process on a hostndash16 bit number ndashReserved ports ( 0 -1024 )
IP AddressIP Address Data StructureData Structurestruct 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] Padding 0
struct in_addr unsigned long s_addr 4 bytes
Generic Socket AddressGeneric Socket Address
bull The sockets API is generic
bull There must be a generic way to specify endpoint addresses
bull TCPIP requires an IP address and a port number for each endpoint address
Generic socket addressesGeneric socket addresses
struct sockaddr
uint8_t sa_len
sa_family_t sa_family
char sa_data[14]
bull sa_family specifies the address typebull sa_data specifies the address value
bull We donrsquot need to deal with sockaddr structures since we will only deal with a real protocol family
bull We can use sockaddr_in structures
BUT Convert this socket address structure into generic one using type casting
Generic Socket AddressGeneric Socket Address
sin_lensin_lensa_lensa_len
sa_familysa_family
sa_datasa_data
AF_INET
sin_port
sin_addr
sin_zero
sockaddrsockaddr sockaddr_insockaddr_in
Network Programming Network Programming FunctionsFunctions
bull Byte Ordering bull Byte Manipulation functionsbull Addressingbull Socket system calls
Byte Ordering of IntegersByte Ordering of Integersbull Different CPU architectures have different
byte ordering
D3
high-order byte low-order byte
memoryaddress A
memoryaddress A +1
Stored at little-endian computer
Stored at big-endian computer
low-order byte high-order byte
F2Integer representation (2 byte)
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
SocketsSocketsbull Sockets provide mechanisms to communicate
between computers across a network
bull There are different kind of sockets
bullBerkeley sockets is the most popular Internet Socketndash runs on Linux FreeBSD Windows
Network APINetwork APIbull Operating system provides Application
Programming Interface (API) for network application
bull API is defined by a set of function types data structures and constants
bull Application Programming Interface for networks is called socket
Internet SocketsInternet Sockets
bullSupport stream and datagram packets (eg TCP UDP IP)
bullIs Similar to UNIX file IO API
bullBased on C
Types of Internet SocketsTypes of Internet Socketsbull Different types of sockets implement different
communication types (stream vs datagram)bull Type of socket stream socket
ndash connection-orientedndash two way communicationndash reliable (error free) in order deliveryndash can use the Transmission Control Protocol
(TCP)ndash eg telnet http
bull Type of socket datagram socketndash connectionless does not maintain an open
connection each packet is independentndash can use the User Datagram Protocol (UDP)ndash eg IP telephony
Data typesData types
int8_t signed 8bit intuint8_t unsigned 8 bit intint16_t signed 16 bit intuint16_t unsigned 16 bit intint32_t signed 32 bit intuint32_t unsigned 32 bit int
u_char u_short u_int u_long
More data typesMore data typessa_family_t address familysocklen_t length of structin_addr_t IPv4 addressin_port_t IP port number
Naming and AddressingNaming and Addressingbull Host name
ndash identifies a single host ndashvariable length string (eg
wwwberkeleyedu)ndash is mapped to one or more IP addresses
bull IP Addressndashwritten as dotted octets (eg 10001)ndash32 bits Not a number But often needs to
be converted to a 32-bit to usebull Port number
ndash identifies a process on a hostndash16 bit number ndashReserved ports ( 0 -1024 )
IP AddressIP Address Data StructureData Structurestruct 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] Padding 0
struct in_addr unsigned long s_addr 4 bytes
Generic Socket AddressGeneric Socket Address
bull The sockets API is generic
bull There must be a generic way to specify endpoint addresses
bull TCPIP requires an IP address and a port number for each endpoint address
Generic socket addressesGeneric socket addresses
struct sockaddr
uint8_t sa_len
sa_family_t sa_family
char sa_data[14]
bull sa_family specifies the address typebull sa_data specifies the address value
bull We donrsquot need to deal with sockaddr structures since we will only deal with a real protocol family
bull We can use sockaddr_in structures
BUT Convert this socket address structure into generic one using type casting
Generic Socket AddressGeneric Socket Address
sin_lensin_lensa_lensa_len
sa_familysa_family
sa_datasa_data
AF_INET
sin_port
sin_addr
sin_zero
sockaddrsockaddr sockaddr_insockaddr_in
Network Programming Network Programming FunctionsFunctions
bull Byte Ordering bull Byte Manipulation functionsbull Addressingbull Socket system calls
Byte Ordering of IntegersByte Ordering of Integersbull Different CPU architectures have different
byte ordering
D3
high-order byte low-order byte
memoryaddress A
memoryaddress A +1
Stored at little-endian computer
Stored at big-endian computer
low-order byte high-order byte
F2Integer representation (2 byte)
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Network APINetwork APIbull Operating system provides Application
Programming Interface (API) for network application
bull API is defined by a set of function types data structures and constants
bull Application Programming Interface for networks is called socket
Internet SocketsInternet Sockets
bullSupport stream and datagram packets (eg TCP UDP IP)
bullIs Similar to UNIX file IO API
bullBased on C
Types of Internet SocketsTypes of Internet Socketsbull Different types of sockets implement different
communication types (stream vs datagram)bull Type of socket stream socket
ndash connection-orientedndash two way communicationndash reliable (error free) in order deliveryndash can use the Transmission Control Protocol
(TCP)ndash eg telnet http
bull Type of socket datagram socketndash connectionless does not maintain an open
connection each packet is independentndash can use the User Datagram Protocol (UDP)ndash eg IP telephony
Data typesData types
int8_t signed 8bit intuint8_t unsigned 8 bit intint16_t signed 16 bit intuint16_t unsigned 16 bit intint32_t signed 32 bit intuint32_t unsigned 32 bit int
u_char u_short u_int u_long
More data typesMore data typessa_family_t address familysocklen_t length of structin_addr_t IPv4 addressin_port_t IP port number
Naming and AddressingNaming and Addressingbull Host name
ndash identifies a single host ndashvariable length string (eg
wwwberkeleyedu)ndash is mapped to one or more IP addresses
bull IP Addressndashwritten as dotted octets (eg 10001)ndash32 bits Not a number But often needs to
be converted to a 32-bit to usebull Port number
ndash identifies a process on a hostndash16 bit number ndashReserved ports ( 0 -1024 )
IP AddressIP Address Data StructureData Structurestruct 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] Padding 0
struct in_addr unsigned long s_addr 4 bytes
Generic Socket AddressGeneric Socket Address
bull The sockets API is generic
bull There must be a generic way to specify endpoint addresses
bull TCPIP requires an IP address and a port number for each endpoint address
Generic socket addressesGeneric socket addresses
struct sockaddr
uint8_t sa_len
sa_family_t sa_family
char sa_data[14]
bull sa_family specifies the address typebull sa_data specifies the address value
bull We donrsquot need to deal with sockaddr structures since we will only deal with a real protocol family
bull We can use sockaddr_in structures
BUT Convert this socket address structure into generic one using type casting
Generic Socket AddressGeneric Socket Address
sin_lensin_lensa_lensa_len
sa_familysa_family
sa_datasa_data
AF_INET
sin_port
sin_addr
sin_zero
sockaddrsockaddr sockaddr_insockaddr_in
Network Programming Network Programming FunctionsFunctions
bull Byte Ordering bull Byte Manipulation functionsbull Addressingbull Socket system calls
Byte Ordering of IntegersByte Ordering of Integersbull Different CPU architectures have different
byte ordering
D3
high-order byte low-order byte
memoryaddress A
memoryaddress A +1
Stored at little-endian computer
Stored at big-endian computer
low-order byte high-order byte
F2Integer representation (2 byte)
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Internet SocketsInternet Sockets
bullSupport stream and datagram packets (eg TCP UDP IP)
bullIs Similar to UNIX file IO API
bullBased on C
Types of Internet SocketsTypes of Internet Socketsbull Different types of sockets implement different
communication types (stream vs datagram)bull Type of socket stream socket
ndash connection-orientedndash two way communicationndash reliable (error free) in order deliveryndash can use the Transmission Control Protocol
(TCP)ndash eg telnet http
bull Type of socket datagram socketndash connectionless does not maintain an open
connection each packet is independentndash can use the User Datagram Protocol (UDP)ndash eg IP telephony
Data typesData types
int8_t signed 8bit intuint8_t unsigned 8 bit intint16_t signed 16 bit intuint16_t unsigned 16 bit intint32_t signed 32 bit intuint32_t unsigned 32 bit int
u_char u_short u_int u_long
More data typesMore data typessa_family_t address familysocklen_t length of structin_addr_t IPv4 addressin_port_t IP port number
Naming and AddressingNaming and Addressingbull Host name
ndash identifies a single host ndashvariable length string (eg
wwwberkeleyedu)ndash is mapped to one or more IP addresses
bull IP Addressndashwritten as dotted octets (eg 10001)ndash32 bits Not a number But often needs to
be converted to a 32-bit to usebull Port number
ndash identifies a process on a hostndash16 bit number ndashReserved ports ( 0 -1024 )
IP AddressIP Address Data StructureData Structurestruct 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] Padding 0
struct in_addr unsigned long s_addr 4 bytes
Generic Socket AddressGeneric Socket Address
bull The sockets API is generic
bull There must be a generic way to specify endpoint addresses
bull TCPIP requires an IP address and a port number for each endpoint address
Generic socket addressesGeneric socket addresses
struct sockaddr
uint8_t sa_len
sa_family_t sa_family
char sa_data[14]
bull sa_family specifies the address typebull sa_data specifies the address value
bull We donrsquot need to deal with sockaddr structures since we will only deal with a real protocol family
bull We can use sockaddr_in structures
BUT Convert this socket address structure into generic one using type casting
Generic Socket AddressGeneric Socket Address
sin_lensin_lensa_lensa_len
sa_familysa_family
sa_datasa_data
AF_INET
sin_port
sin_addr
sin_zero
sockaddrsockaddr sockaddr_insockaddr_in
Network Programming Network Programming FunctionsFunctions
bull Byte Ordering bull Byte Manipulation functionsbull Addressingbull Socket system calls
Byte Ordering of IntegersByte Ordering of Integersbull Different CPU architectures have different
byte ordering
D3
high-order byte low-order byte
memoryaddress A
memoryaddress A +1
Stored at little-endian computer
Stored at big-endian computer
low-order byte high-order byte
F2Integer representation (2 byte)
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Types of Internet SocketsTypes of Internet Socketsbull Different types of sockets implement different
communication types (stream vs datagram)bull Type of socket stream socket
ndash connection-orientedndash two way communicationndash reliable (error free) in order deliveryndash can use the Transmission Control Protocol
(TCP)ndash eg telnet http
bull Type of socket datagram socketndash connectionless does not maintain an open
connection each packet is independentndash can use the User Datagram Protocol (UDP)ndash eg IP telephony
Data typesData types
int8_t signed 8bit intuint8_t unsigned 8 bit intint16_t signed 16 bit intuint16_t unsigned 16 bit intint32_t signed 32 bit intuint32_t unsigned 32 bit int
u_char u_short u_int u_long
More data typesMore data typessa_family_t address familysocklen_t length of structin_addr_t IPv4 addressin_port_t IP port number
Naming and AddressingNaming and Addressingbull Host name
ndash identifies a single host ndashvariable length string (eg
wwwberkeleyedu)ndash is mapped to one or more IP addresses
bull IP Addressndashwritten as dotted octets (eg 10001)ndash32 bits Not a number But often needs to
be converted to a 32-bit to usebull Port number
ndash identifies a process on a hostndash16 bit number ndashReserved ports ( 0 -1024 )
IP AddressIP Address Data StructureData Structurestruct 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] Padding 0
struct in_addr unsigned long s_addr 4 bytes
Generic Socket AddressGeneric Socket Address
bull The sockets API is generic
bull There must be a generic way to specify endpoint addresses
bull TCPIP requires an IP address and a port number for each endpoint address
Generic socket addressesGeneric socket addresses
struct sockaddr
uint8_t sa_len
sa_family_t sa_family
char sa_data[14]
bull sa_family specifies the address typebull sa_data specifies the address value
bull We donrsquot need to deal with sockaddr structures since we will only deal with a real protocol family
bull We can use sockaddr_in structures
BUT Convert this socket address structure into generic one using type casting
Generic Socket AddressGeneric Socket Address
sin_lensin_lensa_lensa_len
sa_familysa_family
sa_datasa_data
AF_INET
sin_port
sin_addr
sin_zero
sockaddrsockaddr sockaddr_insockaddr_in
Network Programming Network Programming FunctionsFunctions
bull Byte Ordering bull Byte Manipulation functionsbull Addressingbull Socket system calls
Byte Ordering of IntegersByte Ordering of Integersbull Different CPU architectures have different
byte ordering
D3
high-order byte low-order byte
memoryaddress A
memoryaddress A +1
Stored at little-endian computer
Stored at big-endian computer
low-order byte high-order byte
F2Integer representation (2 byte)
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Data typesData types
int8_t signed 8bit intuint8_t unsigned 8 bit intint16_t signed 16 bit intuint16_t unsigned 16 bit intint32_t signed 32 bit intuint32_t unsigned 32 bit int
u_char u_short u_int u_long
More data typesMore data typessa_family_t address familysocklen_t length of structin_addr_t IPv4 addressin_port_t IP port number
Naming and AddressingNaming and Addressingbull Host name
ndash identifies a single host ndashvariable length string (eg
wwwberkeleyedu)ndash is mapped to one or more IP addresses
bull IP Addressndashwritten as dotted octets (eg 10001)ndash32 bits Not a number But often needs to
be converted to a 32-bit to usebull Port number
ndash identifies a process on a hostndash16 bit number ndashReserved ports ( 0 -1024 )
IP AddressIP Address Data StructureData Structurestruct 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] Padding 0
struct in_addr unsigned long s_addr 4 bytes
Generic Socket AddressGeneric Socket Address
bull The sockets API is generic
bull There must be a generic way to specify endpoint addresses
bull TCPIP requires an IP address and a port number for each endpoint address
Generic socket addressesGeneric socket addresses
struct sockaddr
uint8_t sa_len
sa_family_t sa_family
char sa_data[14]
bull sa_family specifies the address typebull sa_data specifies the address value
bull We donrsquot need to deal with sockaddr structures since we will only deal with a real protocol family
bull We can use sockaddr_in structures
BUT Convert this socket address structure into generic one using type casting
Generic Socket AddressGeneric Socket Address
sin_lensin_lensa_lensa_len
sa_familysa_family
sa_datasa_data
AF_INET
sin_port
sin_addr
sin_zero
sockaddrsockaddr sockaddr_insockaddr_in
Network Programming Network Programming FunctionsFunctions
bull Byte Ordering bull Byte Manipulation functionsbull Addressingbull Socket system calls
Byte Ordering of IntegersByte Ordering of Integersbull Different CPU architectures have different
byte ordering
D3
high-order byte low-order byte
memoryaddress A
memoryaddress A +1
Stored at little-endian computer
Stored at big-endian computer
low-order byte high-order byte
F2Integer representation (2 byte)
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
More data typesMore data typessa_family_t address familysocklen_t length of structin_addr_t IPv4 addressin_port_t IP port number
Naming and AddressingNaming and Addressingbull Host name
ndash identifies a single host ndashvariable length string (eg
wwwberkeleyedu)ndash is mapped to one or more IP addresses
bull IP Addressndashwritten as dotted octets (eg 10001)ndash32 bits Not a number But often needs to
be converted to a 32-bit to usebull Port number
ndash identifies a process on a hostndash16 bit number ndashReserved ports ( 0 -1024 )
IP AddressIP Address Data StructureData Structurestruct 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] Padding 0
struct in_addr unsigned long s_addr 4 bytes
Generic Socket AddressGeneric Socket Address
bull The sockets API is generic
bull There must be a generic way to specify endpoint addresses
bull TCPIP requires an IP address and a port number for each endpoint address
Generic socket addressesGeneric socket addresses
struct sockaddr
uint8_t sa_len
sa_family_t sa_family
char sa_data[14]
bull sa_family specifies the address typebull sa_data specifies the address value
bull We donrsquot need to deal with sockaddr structures since we will only deal with a real protocol family
bull We can use sockaddr_in structures
BUT Convert this socket address structure into generic one using type casting
Generic Socket AddressGeneric Socket Address
sin_lensin_lensa_lensa_len
sa_familysa_family
sa_datasa_data
AF_INET
sin_port
sin_addr
sin_zero
sockaddrsockaddr sockaddr_insockaddr_in
Network Programming Network Programming FunctionsFunctions
bull Byte Ordering bull Byte Manipulation functionsbull Addressingbull Socket system calls
Byte Ordering of IntegersByte Ordering of Integersbull Different CPU architectures have different
byte ordering
D3
high-order byte low-order byte
memoryaddress A
memoryaddress A +1
Stored at little-endian computer
Stored at big-endian computer
low-order byte high-order byte
F2Integer representation (2 byte)
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Naming and AddressingNaming and Addressingbull Host name
ndash identifies a single host ndashvariable length string (eg
wwwberkeleyedu)ndash is mapped to one or more IP addresses
bull IP Addressndashwritten as dotted octets (eg 10001)ndash32 bits Not a number But often needs to
be converted to a 32-bit to usebull Port number
ndash identifies a process on a hostndash16 bit number ndashReserved ports ( 0 -1024 )
IP AddressIP Address Data StructureData Structurestruct 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] Padding 0
struct in_addr unsigned long s_addr 4 bytes
Generic Socket AddressGeneric Socket Address
bull The sockets API is generic
bull There must be a generic way to specify endpoint addresses
bull TCPIP requires an IP address and a port number for each endpoint address
Generic socket addressesGeneric socket addresses
struct sockaddr
uint8_t sa_len
sa_family_t sa_family
char sa_data[14]
bull sa_family specifies the address typebull sa_data specifies the address value
bull We donrsquot need to deal with sockaddr structures since we will only deal with a real protocol family
bull We can use sockaddr_in structures
BUT Convert this socket address structure into generic one using type casting
Generic Socket AddressGeneric Socket Address
sin_lensin_lensa_lensa_len
sa_familysa_family
sa_datasa_data
AF_INET
sin_port
sin_addr
sin_zero
sockaddrsockaddr sockaddr_insockaddr_in
Network Programming Network Programming FunctionsFunctions
bull Byte Ordering bull Byte Manipulation functionsbull Addressingbull Socket system calls
Byte Ordering of IntegersByte Ordering of Integersbull Different CPU architectures have different
byte ordering
D3
high-order byte low-order byte
memoryaddress A
memoryaddress A +1
Stored at little-endian computer
Stored at big-endian computer
low-order byte high-order byte
F2Integer representation (2 byte)
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
IP AddressIP Address Data StructureData Structurestruct 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] Padding 0
struct in_addr unsigned long s_addr 4 bytes
Generic Socket AddressGeneric Socket Address
bull The sockets API is generic
bull There must be a generic way to specify endpoint addresses
bull TCPIP requires an IP address and a port number for each endpoint address
Generic socket addressesGeneric socket addresses
struct sockaddr
uint8_t sa_len
sa_family_t sa_family
char sa_data[14]
bull sa_family specifies the address typebull sa_data specifies the address value
bull We donrsquot need to deal with sockaddr structures since we will only deal with a real protocol family
bull We can use sockaddr_in structures
BUT Convert this socket address structure into generic one using type casting
Generic Socket AddressGeneric Socket Address
sin_lensin_lensa_lensa_len
sa_familysa_family
sa_datasa_data
AF_INET
sin_port
sin_addr
sin_zero
sockaddrsockaddr sockaddr_insockaddr_in
Network Programming Network Programming FunctionsFunctions
bull Byte Ordering bull Byte Manipulation functionsbull Addressingbull Socket system calls
Byte Ordering of IntegersByte Ordering of Integersbull Different CPU architectures have different
byte ordering
D3
high-order byte low-order byte
memoryaddress A
memoryaddress A +1
Stored at little-endian computer
Stored at big-endian computer
low-order byte high-order byte
F2Integer representation (2 byte)
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Generic Socket AddressGeneric Socket Address
bull The sockets API is generic
bull There must be a generic way to specify endpoint addresses
bull TCPIP requires an IP address and a port number for each endpoint address
Generic socket addressesGeneric socket addresses
struct sockaddr
uint8_t sa_len
sa_family_t sa_family
char sa_data[14]
bull sa_family specifies the address typebull sa_data specifies the address value
bull We donrsquot need to deal with sockaddr structures since we will only deal with a real protocol family
bull We can use sockaddr_in structures
BUT Convert this socket address structure into generic one using type casting
Generic Socket AddressGeneric Socket Address
sin_lensin_lensa_lensa_len
sa_familysa_family
sa_datasa_data
AF_INET
sin_port
sin_addr
sin_zero
sockaddrsockaddr sockaddr_insockaddr_in
Network Programming Network Programming FunctionsFunctions
bull Byte Ordering bull Byte Manipulation functionsbull Addressingbull Socket system calls
Byte Ordering of IntegersByte Ordering of Integersbull Different CPU architectures have different
byte ordering
D3
high-order byte low-order byte
memoryaddress A
memoryaddress A +1
Stored at little-endian computer
Stored at big-endian computer
low-order byte high-order byte
F2Integer representation (2 byte)
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Generic socket addressesGeneric socket addresses
struct sockaddr
uint8_t sa_len
sa_family_t sa_family
char sa_data[14]
bull sa_family specifies the address typebull sa_data specifies the address value
bull We donrsquot need to deal with sockaddr structures since we will only deal with a real protocol family
bull We can use sockaddr_in structures
BUT Convert this socket address structure into generic one using type casting
Generic Socket AddressGeneric Socket Address
sin_lensin_lensa_lensa_len
sa_familysa_family
sa_datasa_data
AF_INET
sin_port
sin_addr
sin_zero
sockaddrsockaddr sockaddr_insockaddr_in
Network Programming Network Programming FunctionsFunctions
bull Byte Ordering bull Byte Manipulation functionsbull Addressingbull Socket system calls
Byte Ordering of IntegersByte Ordering of Integersbull Different CPU architectures have different
byte ordering
D3
high-order byte low-order byte
memoryaddress A
memoryaddress A +1
Stored at little-endian computer
Stored at big-endian computer
low-order byte high-order byte
F2Integer representation (2 byte)
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
bull We donrsquot need to deal with sockaddr structures since we will only deal with a real protocol family
bull We can use sockaddr_in structures
BUT Convert this socket address structure into generic one using type casting
Generic Socket AddressGeneric Socket Address
sin_lensin_lensa_lensa_len
sa_familysa_family
sa_datasa_data
AF_INET
sin_port
sin_addr
sin_zero
sockaddrsockaddr sockaddr_insockaddr_in
Network Programming Network Programming FunctionsFunctions
bull Byte Ordering bull Byte Manipulation functionsbull Addressingbull Socket system calls
Byte Ordering of IntegersByte Ordering of Integersbull Different CPU architectures have different
byte ordering
D3
high-order byte low-order byte
memoryaddress A
memoryaddress A +1
Stored at little-endian computer
Stored at big-endian computer
low-order byte high-order byte
F2Integer representation (2 byte)
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
sin_lensin_lensa_lensa_len
sa_familysa_family
sa_datasa_data
AF_INET
sin_port
sin_addr
sin_zero
sockaddrsockaddr sockaddr_insockaddr_in
Network Programming Network Programming FunctionsFunctions
bull Byte Ordering bull Byte Manipulation functionsbull Addressingbull Socket system calls
Byte Ordering of IntegersByte Ordering of Integersbull Different CPU architectures have different
byte ordering
D3
high-order byte low-order byte
memoryaddress A
memoryaddress A +1
Stored at little-endian computer
Stored at big-endian computer
low-order byte high-order byte
F2Integer representation (2 byte)
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Network Programming Network Programming FunctionsFunctions
bull Byte Ordering bull Byte Manipulation functionsbull Addressingbull Socket system calls
Byte Ordering of IntegersByte Ordering of Integersbull Different CPU architectures have different
byte ordering
D3
high-order byte low-order byte
memoryaddress A
memoryaddress A +1
Stored at little-endian computer
Stored at big-endian computer
low-order byte high-order byte
F2Integer representation (2 byte)
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Byte Ordering of IntegersByte Ordering of Integersbull Different CPU architectures have different
byte ordering
D3
high-order byte low-order byte
memoryaddress A
memoryaddress A +1
Stored at little-endian computer
Stored at big-endian computer
low-order byte high-order byte
F2Integer representation (2 byte)
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Byte OrderByte Order
bull Byte Ordering
bull 1048708 Big Endian vs Little Endian
bull 1048708 Little Endian (Intel DEC)1048708 Least significant byte of word is stored in the lowest memory address
bull 1048708 Big Endian (Sun SGI HP)1048708 Most significant byte of word is stored in the lowest
memory address
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Network Byte Order FunctionsNetwork Byte Order Functionslsquo16- and 32-bit conversion functions (for platformindependence)1048708 Examplesint m nshort int stm = ntohl (n) net-to-host long (32-bit)
translations = ntohs (t) net-to-host short (16-bit)
translationn = htonl (m) host-to-net long (32-bit)
translationt = htons (s) host-to-net short (16-bit)
translation
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Byte Manipulation Byte Manipulation FunctionsFunctions
bull Void bzero (void dest size_t nbytes)
bull Void bcopy (const void src void dest size_t nbytes)
bull Int bcmp (const void ptr1 const void ptr2 size_t nbytes)
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
IPv4 Address ConversionIPv4 Address Conversion
int inet_aton( char struct in_addr )
Convert ASCII dotted-decimal IP address to network byte order 32 bit value Returns 1 on success 0 on failure
char inet_ntoa(struct in_addr)
Convert network byte ordered value to ASCII dotted-decimal (a string)
a ndash ASCII dotted-decimal ipv4 addressn ndash32 bit binary ipv4 address in network byte
order
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
inet_ntop inet_pton ndash bull convert IPv4 and IPv6 addresses between binary and text form
bull include ltarpainethgt
bull int inet_pton(int af const char src void dst)bull const char inet_ntop(int af const void src char dst socklen_t
size)
bull af Specifies the family of the address to be converted AF_INET and AF_INET6
bull src ndash (Input) The pointer to the null-terminated character string that contains the text
presentation form of an IPv4 IPV6 address dst ndash (Output) The pointer to a buffer into which the function stores the numeric
address The calling application must ensure that the buffer referred to by dst is large enough to hold the numeric address (4 bytes for AF_INET or 16 bytes for AF_INET6)
size bull (Input) The size of the buffer pointed at by dst
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Address AccessConversionAddress AccessConversionFunctionsFunctions
bull 1048708 All binary values are network byte orderedbull struct hostent gethostbyname (const
charhostname)bull 1048708 Translate English host name to IP address (uses
DNS)bull struct hostent gethostbyaddr (const charaddr size_t len int family)bull 1048708 Translate IP address to English host name (not
secure)
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Socket codeSocket codebull socket()- creates a TCP or UDP socketbull bind() ndash binds a socket to an address or file
namebull connect()- connect to another process via a
socketbull listen() ndash wait for connections over a socketbull accept() ndash create a communication socket
with a process which has connected to youbull send() ndash sends a stringinformation over a
socketbull recv() ndash receive a stringinformation which
was sent over a socketbull sendto() ndash UDP version of send()bull recvfrom() ndash UDP version of recv()bull unlink() ndash remove a Unix local domain socketbull close() ndash to close a socket
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Simple TCP Client-Server ExampleSimple TCP Client-Server Example
Client Serverrequest
response
socket()connect()write()
read()close()
socket()bind()listen()accept()
read()
write()
read()close()
Connectionestablishment
Data response
Data request
End-of-file notification
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Creating a SocketCreating a Socket
int socket(int familyint typeint proto)
bullfamily specifies the protocol family (AF_INET for TCPIP)
bull type specifies the type of service (SOCK_STREAM SOCK_DGRAM)
bull protocol specifies the specific protocol (usually 0 which means the default)
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
socket()socket()
bull The socket() system call returns a socket descriptor (small integer) or -1 on error
bull socket() allocates resources needed for a communication endpoint - but it does not deal with endpoint addressing
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Bind()Bind()bull The bind() system call is used to
assign an address to an existing socket
bull It tells the os to assign a local IP address and local port number to the socket
int bind( int sockfd const struct sockaddr myaddr
int addrlen)
bull bind returns 0 if successful or -1 on error
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
bind()bind() Example Example
int mysockerrstruct sockaddr_in myaddr
mysock = Socket(AF_INETSOCK_STREAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( portnum )myaddrsin_addr = htonl( ipaddress)
err=bind(mysock (struct sockaddr ) ampmyaddr sizeof(myaddr))
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Uses for Uses for bind()bind()
bull There are a number of uses for bind()
ndash Server would like to bind to a well known address (port number)
ndash Client can bind to a specific port
ndash Client can ask the OS to assign any available port number
myaddrport = htons(0)
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Uses for Uses for bind()bind()
If the computer has multiple network interfaces
bullThere is no realistic way to know the right IP address for bind()
bull specify the IP address as INADDR_ANY this tells the OS to take care of things
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
listen()listen()int listen( int sockfd int backlog)
sockfd is the TCP socket (already bound to an address)
Once we call listen() the OS will queue incoming connections
backlog is the number of incoming connections the kernel should queue for this socket
listen() returns -1 on error (otherwise 0)
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
accept()accept()int accept( int sockfd
struct sockaddr cliaddr socklen_t addrlen)
sockfd is the passive mode TCP socketcliaddr is a pointer to allocated spaceaddrlen is a value-result argument
ndash must be set to the size of cliaddrndash on return will be set to be the number of
used bytes in cliaddr
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
accept()accept()
accept() returns a new socket descriptor (small positive integer) or -1 on error
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Connect()Connect()bull TCP clients can call connect() which
ndash takes care of establishing an endpoint address for the client socketbullNo need to call bind the OS will take
care of assigning the local endpoint address (TCP port number IP address)
ndash Attempts to establish a connection to the specified serverbull3-way handshake
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
connect()connect()
int connect( int sockfd
const struct sockaddr server
socklen_t addrlen)
sockfd is an already created TCP socketserver contains the address of the server
(IP Address and TCP port number)
connect() returns 0 if OK -1 on error
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
connect()connect()
After connection is established IO can be done using the system calls
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Terminating a TCP Terminating a TCP connectionconnection
bull Either end of the connection can call the close() system call
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Value-Result ParametersValue-Result Parametersbull Bind()connect() and sendto() pass a
socket address from the process to the kernel
bull Accept() recvfrom() pass a socket address structure from kernel to the process
bullValue ndash Tells the kernel the size of the structure
bullResult ndash Tells the process how much information the kernel actually stored in the structure
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Concurrent serversConcurrent servers
bull To handle multiple clients at the same time
bull The simplest way is to fork a child process to handle each client
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Fork() and exec()Fork() and exec()bull Pid_t fork(void) - Returns 0 in child process ID of child in parent -
1on errorbull Exec() ndash A process to execute another program - calls fork to create a copy - One of the copy calls exec() to replace itself with
new programbull Six functions - execl xecvexecleexecveexeclp
execvp - Whether file to execute is specified by filename
or pathname - arguments to program listed or thro array of
pointers - whether environment of calling process is
passed or new environment specified
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
bull include ltunistdhgtint execl(const char path const char arg0 (char )0 )int execv(const char path char const argv[])int execle(const char path const char arg0 (char )0 char const envp[])int execve(const char path char const argv[] char const envp[])int execlp(const char file const char arg0 (char )0 )int execvp(const char file char const argv[])
bull The arguments specified by a program with one of the exec functions shall be passed on to the new process image in the corresponding main() arguments
bull The argument path points to a pathname that identifies the new process image file
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
bull sock_ntop - takes a pointer to a socket address structure
looks inside the structure and calls the appropriate function to return the presentation format of the address
bull include unphldquo
bull char sock_ntop(const struct sockaddr sockaddr socklen_t addrlen)
bull Returns non-null pointer if OK NULL on errorbull sockaddr points to a socket address structure whose length is
addrlen bull The function uses its own static buffer to hold the result and
a pointer to this buffer is the return value
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
readn writen and readline Functions bull A read or write on a stream socket might input or output
fewer bytes than requestedbull The reason is that buffer limits might be reached for the
socket in the kernel bull All that is required to input or output the remaining bytes is
for the caller to invoke the read or write function againbull This scenario is always a possibility on a stream socket
with read but is normally seen with write only if the socket is nonblocking
include unphldquobull ssize_t readn(int filedes void buff size_t nbytes)bull ssize_t writen(int filedes const void buff size_t nbytes)bull ssize_t readline(int filedes void buff size_t maxlen)
bull All return number of bytes read or written ndash1 on errorbull Note that our readline function calls the systemrsquos read
function once for every byte of data
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
bull include ltsyssockethgt
bull int getsockname(int socket struct sockaddr address socklen_t address_len)
bull The getsockname() function retrieves the locally-bound name of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the socket has not been bound to a local name the value
stored in the object pointed to by address is unspecified
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
bull include ltsyssockethgt bull int getpeername(int socket struct
sockaddr address socklen_t address_len)
bull The getpeername() function retrieves the peer address of the specified socket stores this address in the sockaddr structure pointed to by the address argument and stores the length of this address in the object pointed to by the address_len argument
bull If the actual length of the address is greater than the length of the supplied sockaddr structure the stored address will be truncated
bull If the protocol permits connections by unbound clients and the peer is not bound then the value stored in the object pointed to by address is unspecified
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Example Client Example Client ProgrammingProgramming
bull Create stream socket (socket() )bull Connect to server (connect() )bull While still connected
ndash send message to server (write() )ndash receive (read() ) data from server
and process it
bull Close TCP connection and Socket (close())
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Server Programming Server Programming SimpleSimple
bull Create stream socket (socket() )bull Bind port to socket (bind() )bull Listen for new client (listen() )bull While
ndash accept user connection and create a new socket (accept() )
ndash data arrives from client (read() )ndash data has to be send to client (write() )
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Creating amp Binding TCP Creating amp Binding TCP SocketSocket
int mysockstruct sockaddr_in myaddr
mysock=socket(PF_INETSOCK_STREAM0)
myaddrsin_family = AF_INETmyaddrsin_port = htons( 80 )myaddrsin_addr = htonl( INADDR_ANY)
bind(mysock(struct sockaddr ) ampmyaddr sizeof(myaddr))
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Reading from a TCP socketReading from a TCP socketint read( int fd char buf int max)
bull By default read() will block until data is available
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Writing to a TCP socketWriting to a TCP socket
int write( int fd char buf int num)
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
socket ( )
bind ( )
recvfrom( )sendto ( )
sendo ( )
recvfrom( )socket ( )
bind ( ) blocks until data received from a client
Server(Connectionless
protocol)
Client
data (request)
data reply
Socket system calls for connectionless protocol
process request
UDP Sockets ProgrammingUDP Sockets Programming
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Typical UDP client codeTypical UDP client codebull Create UDP socket
bull Create sockaddr with address of server
bull Call sendto() sending request to the server No call to bind() is necessary
bull Possibly call recvfrom() (if we need a reply)
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Typical UDP Server codeTypical UDP Server codebull Create UDP socket and bind to well
known address
bull Call recvfrom() to get a request noting the address of the client
bull Process request and send reply back with sendto()
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Creating amp Binding UDP Creating amp Binding UDP SocketSocket
int mysock
struct sockaddr_in myaddr
mysock = socket(PF_INETSOCK_DGRAM0)
myaddrsin_family = AF_INET
myaddrsin_port = htons( 1234 )
myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Sending UDP DatagramsSending UDP Datagramsssize_t sendto( int sockfd
void buff
size_t nbytes
int flags
const struct sockaddr to
socklen_t addrlen)
sockfd is a UDP socketbuff is the address of the data (nbytes
long)to is the address of a sockaddr containing
the destination addressReturn value is the number of bytes sent
or -1 on error
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
Receiving UDP DatagramsReceiving UDP Datagramsssize_t recvfrom( int sockfd
void buffsize_t nbytesint flags
struct sockaddr from socklen_t fromaddrlen)
sockfd is a UDP socketbuff is the address of a buffer (nbytes
long)from is the address of a sockaddrReturn value is the number of bytes received
and put into buff or -1 on error
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
recvfrom()recvfrom()bull If buff is not large enough any extra
data is lost
bull recvfrom doesnrsquot return until there is a datagram available
bull The sockaddr at from is filled in with the address of the sender
bull set fromaddrlen before calling
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
UDP Echo ServerUDP Echo Serverint mysockstruct sockaddr_in myaddr cliaddrchar msgbuf[MAXLEN]socklen_t clilenint msglen
mysock = socket(PF_INETSOCK_DGRAM0)myaddrsin_family = AF_INETmyaddrsin_port = htons( S_PORT )myaddrsin_addr = htonl( INADDR_ANY )
bind(mysock ampmyaddr sizeof(myaddr))while (1) len=sizeof(cliaddr)msglen=recvfrom(mysockmsgbufMAXLEN0cliaddrampclilen)sendto(mysockmsgbufmsglen0cliaddrclilen)
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
socketsocketinclude ltsystypeshgt include ltsyssockethgt int socket(int domain int type int protocol) domain is either AF_UNIX AF_INET or AF_OSI or
AF_UNIX is the Unix domain it is used for communication within a single computer system [AF_LOCAL is the Posix name for AF_UNIX] AF_INET is for communication on the internet to IPv4addresses type is either SOCK_STREAM (TCP connection oriented reliable) or SOCK_DGRAM (UDP datagram unreliable) or SOCK_RAW (IP level)protocol specifies the protocol used It is usually 0 to say we want to use the default protocol for the chosen domain and type
Returns if successful a socket descriptor which is an int It returns -1 in case of failure
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
bindbindinclude ltsystypeshgt include ltsyssockethgt int bind(int sd const struct sockaddr addr int
addrlen) sd File descriptor of local socket as created by the socket function addr Pointer to protocol address structure of this
socket (eg sockaddr_in or sockaddr_un)addrlen Length in bytes of structure referenced by addr Returns an integer the return code (0=success -1=failure)
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
connectconnectinclude ltsystypeshgt include ltsyssockethgt int connect(int sd const struct sockaddr
addr int addrlen) sd file descriptor of local socket
addr pointer to protocol address of other socket (ie the one you want to connect to)
addrlen length in bytes of address structureReturns an integer (0=success -1=failure)
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
listenlistenint listen(int fd int qlen)
fd file descriptor of a socket that has already been bound qlen specifies the maximum number of
connection requests that can wait to be processed by the server while the server is busy servicing another connection request Returns an integer (0=success -1=failure)
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
acceptacceptinclude ltsystypeshgt include ltsyssockethgt int accept(int fd struct sockaddr addressp int addrlen)
fd is an int the file descriptor of the socket the server was listening on [in fact it is called the listening socket] ie on which the server has successfully completed socket bind and listen addressp points to an address It will be filled with address of the calling client We can use this address to determine the IP address and port of the client addrlen is an integer that will contain the actual length of address structure of client Returns an integer representing a new socket (-1 in case of
failure) It is the socket that the server will use from now on to communicate with the client that requested connection [in fact it is called the connected socket] Different calls to accept will result in different connected sockets Remember that the default behaviour for this function is to block the calling process until a connection is actually accepted (you can change that with fcntl)
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
sendtosendto (for sending over UDP) (for sending over UDP)include ltsystypeshgt include ltsyssockethgt int sendto(int sd char buff int len int flags struct
sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer with the information to be sent len size of the message flags usually 0 could be used for priority messages etc addressp address of process we are sending message to addrlen length of message Returns number of characters sent It is -1 in case of failure
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
recvfromrecvfrom (recv for UDP) (recv for UDP)include ltsystypeshgt include ltsyssockethgt int recvfrom (int sd char buff int len int flags
struct sockaddr addressp int addrlen) sd socket file descriptor buff address of buffer where message will be stored len size of buffer flags usually 0 used for priority messages peeking etc addressp buffer that will receive address of process that sent message addrlen contains size of addressp structure Returns number of characters received It is -1 in case of failure
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
sendsendint send(int sockfd const void msg int len
int flags)sockfd is the socket descriptor you want to
send data to (whether its the one returned by socket() or the one you got with accept())msg is a pointer to the data you want to
send It can be any sort of structureflags I am told you should leave this as 0 but see the man page for more infoReturns the number of bytes actually sent
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
recvrecvint recv(int sockfd void buf int len unsigned int
flags)sockfd is the socket descriptor to read frombuf is the buffer to read the information intolen is the maximum length of the buffer and flags can again be set to 0 (See the recv() man
page for flag information)Returns the number of bytes actually read into the buffer or -1 on error
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
gethostbynamegethostbyname ndash info about the hostname (eg ndash info about the hostname (eg ldquowwwmcgillcardquo)ldquowwwmcgillcardquo)
include ltnetdbhgt struct hostent gethostbyname(const char name)As you see it returns a pointer to a struct hostent the layout of which is as followsstruct hostent
char h_name char h_aliases int h_addrtype int h_length char h_addr_list
define h_addr h_addr_list[0]And here are the descriptions of the fields in the struct hostenth_name -- Official name of the hosth_aliases -- A NULL-terminated array of alternate names for the hosth_addrtype -- The type of address being returned usually AF_INETh_length -- The length of the address in bytesh_addr_list -- A zero-terminated array of network addresses for the host Host addresses are in Network Byte Orderh_addr -- The first address in h_addr_list
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
selectselectinclude ltsysselecthgtinclude ltsystimehgt
int select(int maxfdp1 fd_set readset fd_set writeset fd_set exceptset const struct timeval timeout)
maxfdp1 the largest fd from the three fd_sets plus 1
readset set of fdrsquos for sockets you are waiting to read (so eg accept() or recv())
writeset set of fdrsquos for sockets you are waiting to write to (eg you want to send())
exceptset set of fdrsquos yoursquore looking for an exception fromtimeout select will block until either this amount of time has elapsed or one or more sockets from any of the three fd_sets are ready whichever comes first To wait forever timeout should be a NULL pointer to not block at all timeout should contain 0Returns the number of fdrsquos which are ready from readset writeset and exceptset
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
selectselect utilities utilitiesvoid FD_ZERO(fd_set fdset)
Set fdset to be the empty set ndash you should always start by initializing your fd_set to empty
void FD_SET(int fd fd_set fdset)Add file descriptor fd to fdset
void FD_CLR(int fd fd_set fdset)Remove fd from fdset
int FD_ISSET(int fd fd_set fdset)True iff select found that fd was ready (whether it was for reading writing or an exception)
FD_SETSIZE = 256Apparently you canrsquot have more than 256 items in an fd_set This shouldnrsquot be an issue right now I just mention it for completeness
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you
fcntlfcntlinclude ltfcntlhgtint fcntl(int fd int cmd hellip int arg )
fd identifies the socket you wish to altercmd the command to execute F_GETFL will cause fcntl to return an integer which contains all flags for the socket In this case pass 0 for arg
F_SETFL will cause the socketrsquos state to be set according to the flag passed as arg
(There are other options for this See the man page)arg hellip see aboveFor F_GETFL returns the flags for socket fdFor F_SETFL returns gt= 0 for success else lt 0
egflags = fcntl(fd F_GETFL 0)flags |= O_NONBLOCK (to set the socket to non-blocking)
or flags amp= ~O_NONBLOCK (to set the socket back to blocking)
fcntl(fd F_SETFL flags)
Thank you