ccplusplus.com
Learn C, C++ Concepts
Sunday, October 2, 2011
af_inet example
/*********************************************************************** * File : af_inet.c * Author : Saurabh Gupta * Desc : Demonstrating the bind(2) function by establishing * a Specific AF_INET Socket Address * af_inet socket * Source : http://saurabhgupta0527.blogspot.com/2011/07/socket.html * Created : PM 08:32 02 October 2011 * Note : ************************************************************************/ #include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
/* * This function reports the error and * exits back to the shell: */ static void displayError(const char *on_what) { perror(on_what); exit(1); } int main(int argc, char **argv, char **envp) { int z; //Status return code int sck_inet; // Socket struct sockaddr_in adr_inet; // AF_INET int len_inet; // length /* * Create an IPv4 Internet Socket */ sck_inet = socket(AF_INET,SOCK_STREAM,0); if ( sck_inet == -1 ) { displayError("socket()"); } /* * Create an AF_INET address */ memset(&adr_inet, 0, sizeof adr_inet); adr_inet.sin_family = AF_INET; adr_inet.sin_port = htons(9000); inet_aton ("127.0.0.24",&adr_inet.sin_addr); len_inet = sizeof adr_inet; /* * Now bind the address to the socket */ z = bind(sck_inet, (struct sockaddr *)&adr_inet, len_inet); if ( z == -1 ) { displayError("bind()"); } /* * Display all of our bound sockets */ system("netstat -pa --tcp 2>/dev/null | sed -n '1,/^Proto/p;/bind/p'"); close(sck_inet); return 0; } /* * OUTPUT * [sgupta@rhel55x86 af_inet]$ gcc -o af_inet af_inet.c [sgupta@rhel55x86 af_inet]$ ./af_inet Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name [sgupta@rhel55x86 af_inet]$ */
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment