UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2002-07-24 11:14 PM

HectorLasso
Administrator
From: Colombia
Registered: 2002-06-12
Posts: 353

Re: 1.4 - What are Sockets?

int srvsock; // A socket descriptor is just an int 
int peersock; // You need a place to hold your peer sockets 
int len; 
struct sockaddr_in address; 
// Create descriptor 
srvsock = socket(AF_INET, SOCK_STREAM, 0); 
address.sin_port = htons(8080); // Bind to por 8080 
address.sin_addr.s_addr = INADDR_ANY; 
address.sin_family = AF_INET; 
// Bind socket to specific port and address(es) 
bind(srvsock, (void*)&address, sizeof(address)); 
// This socket shall be a server 
listen(srvsock, 10); // 10 is queue length 

// Wait for new connections 
do { 
   len = sizeof(address); 
   // Here address is used to receive the address of the 
   // connecting party 
   peersock = accept(srvsock, &address, &len); 
   // peersock is the socket descriptor used to communicate 
   // to a specific client 
   // In this example, i just send a message, close the 
   // connection and release the file descriptor 
   send(peersock, "Hi there\n", 9, 0); 
   shutdown(peersock, 2); 
   close(peersock); 
} while (1)

Offline

Board footer

Powered by FluxBB