Pages

Monday, December 19, 2016

Sockets in C

Socket function creates an endpoint for communication and returns a descriptor. It has three arguments.

a. Protocol Family : AF_INET,(IPv4 internet protocols), AF_INET6(IPv6 internet protocols),                                              AF_UNIX, AF_LOCAL(Local Communication)
b. Communication Semantics :  SOCK_STREAM(tcp), SOCK_DGRAM(udp)
c. Protocol Type: ip(0), icmp(1),  ospf(89), isis(124)

Information regarding (a) and (b) can be found in man pages (man socket) in Linux.
Information regarding (c) can be found in protocols file in Linux (cat /etc/protocols).

Definition:

int socket(int domain, int type, int protocol);

This method returns a file descriptor on success and -1 on failure. It does not specify where data will be coming from nor where it will be coming, it just provides the interface.

 #include <sys/types.h>
 #include <sys/socket.h>
 #include <stdio.h>
 #include <errno.h>  // for error macros
 
int main(){

        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if(sock != -1){
            printf("Socket created successfully\n");
            close(sock);
        }else if(sock == ENFILE){
            printf("The system limit on total number of open files has been reached\n");
       }
 
}

No comments:

Post a Comment