90 likes | 117 Views
Socket Tutorial. ECS152b Behrooz Khorashadi. Don’t Forget. #include <sys/socket.h> #include <arpa/inet.h>. Socket Construction. int socket( int protocolFamily, int type, int protocol) int sockID = socket(PF_INET, SOCK_STREAM, 0); int sockID = socket(PF_INET, SOCK_DGRAM, 0);
E N D
Socket Tutorial ECS152b Behrooz Khorashadi
Don’t Forget • #include <sys/socket.h> • #include <arpa/inet.h>
Socket Construction • int socket(int protocolFamily, int type, int protocol) • int sockID = socket(PF_INET, SOCK_STREAM, 0); • int sockID = socket(PF_INET, SOCK_DGRAM, 0); • Return >0 or -1 for error • AF_INET or PF_INET
Socket Connection • int connect(int socket, structsockaddr *serveraddress, unsigned address) • connect(sockID, &serv_addr, sizeof(serv_addr)) • serv_addr is actully of type sockaddr_in
Socket Send • int send (int socket, const void * msg, unsigned int msglength, int flag) • int stringlength= strlen(stringUsend) • send(sockID, stringUsend, stringlength, 0) • Send will block until send has completed
Socket Receive • int recv(int socket, void *rcvBuffer, unsigned int bufferLength, int flag) • Recv(sockID, recvBuffer, buffersize-1, 0) • recvBuffer is a char buffer you create of you own size. • You can use a while loop
Socket Close • … close(sockID)… • This should be done on the client side.
More Help • A good place to start Internet • http://www.cs.rpi.edu/courses/sysprog/sockets/sock.html
Struct for Sockets • struct sockaddr_in { short sin_family; /* must be AF_INET */ u_short sin_port; structin_addr sin_addr; char sin_zero[8]; /* Not used, must be zero */ }; • Struct sockaddr{ usigned short sa_family; char some_data[14] };