Find the answer to your Linux question:
Results 1 to 3 of 3
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    begening network programming in linux

    I am living in a hostel in which every room hostel is connected by LAN through router.
    I want to try a simple program I read in a book which is a simple echo like program using
    C and API which includes a server and a client.
    Please guide me through the processes and the basic notion about server and client.

  2. #2

    Here is a sample code to open a socket and read/write on it. By default it open socket on on port 9100 (you can change that).
    This is server part, you use telnet as a client :
    # telnet 9100

    The code call a 'bail' fct wich is simply an error print and exit, you have to write or remove the call.

    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <netdb.h>
    #include <argp.h>

    in main :

    srv_addr = ""; // IP Addr to bind server on
    srv_port = "9100"; // TCP Port to listen to

    // Create server INET/TCP socket and check it
    srv_sock = socket(PF_INET, SOCK_STREAM, 0);
    if (srv_sock == -1) bail("Error in Socket()");

    // Create socket IP address and port
    memset(&srv_sockadr, 0, sizeof(srv_sockadr));
    srv_sockadr.sin_family = AF_INET;
    srv_sockadr.sin_port = htons(atoi(srv_port));
    if (strcmp(srv_addr, "*")!=0)
    srv_sockadr.sin_addr.s_addr = inet_addr(srv_addr);
    if (srv_sockadr.sin_addr.s_addr == INADDR_NONE) bail("Error : Bad address");
    srv_sockadr.sin_addr.s_addr = INADDR_ANY; // Wildcard address

    // Bind server socket on the address and check if OK
    len_inet = sizeof(srv_sockadr);
    z = bind(srv_sock, (struct sockaddr*) &srv_sockadr, len_inet);
    if (z == -1) bail("Error on bind");

    // Put server socket in listenning
    z=listen(srv_sock, 10);
    if (z == -1) bail("Error on listen");

    // Forever loop waiting client cnx
    for (;
    // Accept client socket cnx
    len_inet = sizeof cln_sockadr;
    cln_sock = accept(srv_sock, (struct sockaddr*) &cln_sockadr, &len_inet);
    if (cln_sock == -1) bail ("Error on accept");

    // Open Rd/Wr stream to/from client
    RX = fdopen(cln_sock, "r");
    TX = fdopen(dup(cln_sock), "w");

    // Here put your code to read and write to those streams


    // Close the socket itself

  3. #3
    thanks for the support but I am too new to understand this.
    what I want to know is can make a connection between 2 computers on
    a LAN by making one of them as a server and other as a client.

  4. $spacer_open

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts