- create tcp socket using socket()
- establish connection to server using connect()
- communicate using send() and recv()
- close connection using close()
using address structure 1. sockaddr: generic data type 2. in_addr: internet address 3. sockaddr_in: another view of sockaddr
struct sockaddr_in { unsigned short sin_family; // internet protocol (AF_INET) unsigned short sin_port; // address port (16bits) struct in_addr sin_addr; // internet address (32bits) char sin_zero[8]; // not used }
create a socket
int socket(int protocolFamily, int type, int protocol)
- protocolFamily: always PF_INET for tcp/ip sockets
- type: type of socket (SOCK_STREAM or SOCK_DGRAM)
protocol: socket protocol (IPPROTO_TCP or IPPROTO_UDP)
socket() returns the descriptor of the new socket if no error occurs and -1 otherwise
example
#include <sys/types.h>
#include <sys/socket.h>
int servSock;
if ((servSock= socket(PF_INET,SOCK_STREAM,IPPROTO_TCP))<0)
bind to a socket
int bind(int socket, struct sockaddr *localAddress, unsigned int addressLength)
- socket: socket (returned by socket())
- localAddress: populated sockaddr structure describing local address
addressLength: number of bytes in sockaddr structure - usually just size of (localAddress)
bind() returns 0 if no error and -1 otherwise
example
struct sockaddr_in ServAddr;
ServAddr.sin_family = AF_INET; // internet address family
ServAddr.sin_addr.s_addr = htonl(INADDR_ANY); // any incoming interface
ServAddr.sin_port = htons(ServPort); // local port
if (bind(servSock, (struct sockaddr *) &ServAddr, sizeof(echoServAddr))<0)
/*
include // defins in_addr structure
include //
include //
include //
include //
include //
include //
*/