Socket Programming
Socket Programming
Danish Mukhtar
M.Tech CS
Sockets
- Socket is a data communication endpoint for exchanging data over the
network
More details :
- http://man7.org/linux/man-pages/man2/socket.2.html
Closing a socket:
- Closes a connection (for stream socket)
- Frees up the port used by the socket
Bind()
Assign address to socket
struct sockaddr_in{
unsigned short sin_family; /* Internet protocol (AF_INET) */
unsigned short sin_port; /* Address port (16 bits) */
struct in_addr sin_addr; /* Internet address (32 bits) */
};
struct in_addr {
unsigned long s_addr; /* Internet address (32 bits) */
}
If ( socketfd < 0 ){
cout<<"Error in connection"<<endl;
exit(1);
}
If ( ret < 0 ){
cout<<"Error in Binding"<<endl;
exit(1);
}
Listen()
int status = listen(sockid, queueLimit);
Note:
If a connection request arrives when the queue is full, the client may receive an error
with an indication of ECONNREFUSED.
Establish Connection: connect()
The client establishes a connection with the server by calling connect()
accept() :
More Details :
- https://linux.die.net/man/2/send
Recv():
int count = recv(sockid, recvBuf, bufLen, flags);
Note:
send() and recv() are blocking returns only after data is sent / received
Exchanging data with datagram socket
Sendto():
Client Side :
int x = 10;
send(clientSock, &x, sizeof(x), 0);
Server Side :
int x;
recv(serverSock, &x, sizeof(x), 0);
2 . Sending a file:
fseek ( fp , 0 , SEEK_END);
int size = ftell ( fp );
rewind ( fp );
send ( sockfd , &size, sizeof(file_size), 0);
fclose ( fp );
close( sockfd)
- Receiving Side (Server)
close( sockfd)
close( serverfd)
fclose ( fp );
Multithreaded Server
void main(){
……..
……..
listen ( socketfd , 5 )
while(1){
thread RequestThread(serveRequest,newsocket,newAddr);
}
}
void serveRequest ( int newsoc , struct sockaddr_in newAddr){
// bla bla bla
}