Results 1 to 3 of 3
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 ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 08-04-2010 #1Just Joined!
- Join Date
- May 2010
- Posts
- 22
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.
- 08-04-2010 #2Just Joined!
- Join Date
- Aug 2010
- Posts
- 89
Hello,
Here is a sample code to open a socket and read/write on it. By default it open socket on 127.0.0.1 on port 9100 (you can change that).
This is server part, you use telnet as a client :
# telnet 127.0.0.1 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 = "127.0.0.1"; // 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");
}
else
{
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
fclose(TX);
fclose(RX);
// Close the socket itself
close(cln_sock);
- 08-04-2010 #3Just Joined!
- Join Date
- May 2010
- Posts
- 22
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.


Reply With Quote
