Socket functions
- Open (client)
- sd = socket(family, type, proto);
- bind(sd, localaddr, len);
- connect(sd, serveraddr, len);
- Open (server)
- sd = socket(family, type, proto);
- bind(sd, localaddr, len);
- listen(sd, queuesize);
- sd2 = accept(sd, clientaddr, len);
- Close
- Write
- write(sd, data, len);
- send(sd, data, len, flags);
- sendto(sd, data, len, flags, destaddr, len);
- sendmsg(sd, msgstruct, flags);
- read
- read(sd, buf, len);
- recv(sd, buf, len, flags);
- recvfrom(sd, buf, flags, len, srcaddr, len);
- recvmsg(sd, msgstruct, flags);
- additional system calls used
- gethostbyname(hostname)
- getprotobyname(protocolname)
- htonl(hostnumber)
- htons(portnumber)
Using Sockets
- Connection-Oriented - TCP ( point to point )
- Open a client connection
- sd = socket(PF_INET, SOCK_STREAM, PROTO_TCP);
- create buffers and OS table entries to track connection
- bind(sd, localaddr, len);
- specify the local connection point (optional)
- connect(sd, serveraddr, len);
- initiate a connection
- serveraddr may not go out of scope
- Open a server
- sd = socket(family, type, proto);
- create buffers and OS table entries to track connection
- bind(sd, localaddr, len);
- specify the local connection point for listening
- localaddr may not go out of scope
- listen(sd, queuesize);
- create a queue for incoming (SYN) packets and attach to network
- allows receipt of new requests while processing existing one(s)
- sd2 = accept(sd, clientaddr, len);
- pull next connection request from the queue
- uses new descriptor for I/O so the original can keep listening
- clientaddr may not go out of scope
- Write (server and/or client)
- write(sd, data, len);
- send(sd, data, len, flags);
- either works to send data through the network
- send is used mustly on non-Unix systems
- Read (server and/or client)
- read(sd, buf, len);
- recv(sd, buf, len, flags);
- either works to receive data through the network
- recv is used mustly on non-Unix systems
- Close (server and client)
- close(sd);
- closesocket(sd);
- closesocket used mostly on non-Unix systems
- Connectionless - UDP model ( broadcast )
- doesn't follow strict client/server model
- send/receive instead of read/write
- don't need bind/accept/connect but still uses socket call
- Sender
- sd = socket(PF_INET, SOCK_DGRAM, PROTO_UDP);
- sendto(sd, data, len, flags, destaddr, len);
- (or sendmsg(sd, msgstruct, flags);)
- Receiver
- sd = socket(PF_INET, SOCK_DGRAM, PROTO_UDP);
- recvfrom(sd, buf, flags, len, srcaddr, len);
- (or recvmsg(sd, msgstruct, flags);)
Telnet always makes a pretty good client, just give it the host and port.