ccplusplus.com
Learn C, C++ Concepts
Thursday, September 1, 2011
bind function in C
/* using_bind.c: * bind function example c code * Demonstrating the bind(2) function * by establishing a Specific AF_INET * see the bind function usage below * Socket Address: */ #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 * careful about the argument that we are using in bind function */ 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; }
NOTE If the netstat(1) command on your system does not support the options used in above program, substitute the following call if you have the lsofcommand installed: system("lsof -i tcp | sed -n '1p;/bind/p'");
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment