SocketProgramming 3
SocketProgramming 3
SocketProgramming 3
Srinidhi Varadarajan
Client-server paradigm
Client:
application
transport
initiates contact with server network
data link
(“speaks first”) physical
Network
Process Process
A B
Ports (Sockets)
What do you need for socket communication ?
Basically 4 parameters
– Source Identifier (IP address)
– Source Port
– Destination Identifier
– Destination Port
Communication
semantics:
SOCK_STREAM or
SOCK_DGRAM
Server:
int socket(int domain, int type, int protocol)
int bind (int socket, struct sockaddr *address, int addr_len)
int listen (int socket, int backlog)
int accept (int socket, struct sockaddr *address, int *addr_len)
Message Passing
int send (int socket, char *message, int msg_len, int
flags) (TCP)
int sendto (int socket, void *msg, int len, int
flags, struct sockaddr * to,
int tolen ); (UDP)
int write(int socket, void *msg, int len); /* TCP */
new connection
write() Data read()
close() close()
Network Byte Order
Network byte order is most-significant
byte first
Byte ordering at a host may differ
Utility functions
– htons(): Host-to-network byte order for a short
word (2 bytes)
– htonl(): Host-to-network byte order for a long
word (4 bytes)
– ntohs(): Network-to-host byte order for a short
word
– ntohl(): Network-to-host byte order for a long
word
Some Other “Utility” Functions
gethostname() -- get name of local host
getpeername() -- get address of remote
host
getsockname() -- get local address of
socket
getXbyY() -- get protocol, host, or service
number using known number, address, or
port, respectively
getsockopt() -- get current socket options
setsockopt() -- set socket options
ioctl() -- retrieve or set socket information
Some Other “Utility” Functions
inet_addr() -- convert “dotted”
character string form of IP address to
internal binary form
inet_ntoa() -- convert internal binary
form of IP address to “dotted”
character string form
Address Data Structures
struct sockaddr {
u_short sa_family; // type of address
char sa_data[14]; // value of address
}
struct sockaddr_in {
u_short sa_family; // type of address (AF_INET)
u_short sa_port; // protocol port number
struct in_addr sin_addr; // IP address
char sin_zero[8]; // unused (set to zero)
}
sockaddr_in is specific instance for the Internet address
family