473,395 Members | 1,613 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Linux Sockets and POSIX threads example

Hi,
I am trying to encapsulate Linux sockets and POSIX threads in C++ classes (I work in Knoppix, using KDevelop). Since sockets and threads are new to me, I searched for example code and found the following:

Expand|Select|Wrap|Line Numbers
  1.  
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <errno.h>
  6. #include <netdb.h>
  7. #include <signal.h>
  8. #include <fcntl.h>
  9. #include <netinet/ip.h>
  10. #include <pthread.h>
  11.  
  12. struct sockaddr_in getipa(const char*, int);
  13. void printerror(const char*);
  14.  
  15. void* runclient(void*);
  16. void* runserver(void*);
  17.  
  18. int main(){
  19.     pthread_t server;
  20.     pthread_t client;
  21.  
  22.     if(pthread_create(&server, NULL, runserver, NULL) != 0){
  23.         puts("Could not create server thread");
  24.  
  25.         return EXIT_FAILURE;
  26.     }
  27.  
  28.     if(pthread_create(&client, NULL, runclient, NULL) != 0){
  29.         puts("Could not create client thread");
  30.  
  31.         return EXIT_FAILURE;
  32.     }
  33.  
  34.     pthread_join(server, NULL);
  35.     pthread_join(client, NULL);
  36.  
  37.     return EXIT_SUCCESS;
  38. }
  39.  
  40. struct sockaddr_in getipa(const char* hostname, int port){
  41.     struct sockaddr_in ipa;
  42.     ipa.sin_family = AF_INET;
  43.     ipa.sin_port = htons(port);
  44.  
  45.     struct hostent* localhost = gethostbyname(hostname);
  46.     if(!localhost){
  47.         printerror("resolveing localhost");
  48.  
  49.         return ipa;
  50.     }
  51.  
  52.     char* addr = localhost->h_addr_list[0];
  53.     memcpy(&ipa.sin_addr.s_addr, addr, sizeof addr);
  54.  
  55.     return ipa;
  56. }
  57.  
  58. void printerror(const char* action){
  59.     int errnum = errno;
  60.     errno = 0;
  61.  
  62.     if(errnum > 0){
  63.         printf("An error occured while %s.nError code: %inError description: %sn",
  64.                 action, errnum, strerror(errnum));
  65.     }else if(h_errno > 0){
  66.         printf("An error occured while %s.nError code: %inError description: %sn",
  67.                 action, h_errno, hstrerror(h_errno));
  68.  
  69.         h_errno = 0;
  70.     }else{
  71.         printf("An error occured while %s.n There is no error data.n", action);
  72.     }
  73. }
  74.  
  75. void* runserver(void* context){
  76.     struct protoent* tcp;
  77.     tcp = getprotobyname("tcp");
  78.  
  79.     int sfd = socket(PF_INET, SOCK_STREAM, tcp->p_proto);
  80.     if(sfd == -1){
  81.         printerror("createing a tcp socket");
  82.  
  83.         return NULL;
  84.     }
  85.  
  86.     struct sockaddr_in isa = getipa("localhost", 1025);
  87.  
  88.     if(bind(sfd, (struct sockaddr*)&isa, sizeof isa) == -1){
  89.         printerror("binding socket to IP address");
  90.  
  91.         return NULL;
  92.     }
  93.  
  94.     if(listen(sfd, 1) == -1){
  95.         printerror("setting socket to listen");
  96.  
  97.         return NULL;
  98.     }
  99.  
  100.     int cfd = accept(sfd, NULL, NULL);
  101.  
  102.     if(cfd == -1){
  103.         if(errno == EAGAIN || errno == EWOULDBLOCK){
  104.             puts("SIGIO recieved for listen socket, but don't know why.");
  105.         }else{
  106.             printerror("accepting a connection");
  107.  
  108.             return NULL;
  109.         }
  110.     }
  111.  
  112.     char msg[] = "Message to be sent";
  113.  
  114.     if(send(cfd, (void*) msg, sizeof msg, MSG_NOSIGNAL) == -1){
  115.         printerror("sending message to client");
  116.     }
  117.  
  118.     shutdown(cfd, SHUT_RDWR);
  119.  
  120.     return NULL;
  121. }
  122.  
  123. void* runclient(void* context){
  124.     struct protoent* tcp;
  125.     tcp = getprotobyname("tcp");
  126.  
  127.     int sfd = socket(PF_INET, SOCK_STREAM, tcp->p_proto);
  128.     if(sfd == -1){
  129.         printerror("createing a tcp socket");
  130.  
  131.         return NULL;
  132.     }
  133.  
  134.     struct sockaddr_in isa = getipa("localhost", 1025);
  135.  
  136.     if(connect(sfd, (struct sockaddr*)&isa, sizeof isa) == -1){
  137.         printerror("connecting to server");
  138.  
  139.         return NULL;
  140.     }
  141.  
  142.     char buff[255];
  143.     ssize_t size = recv(sfd, (void*)buff, sizeof buff, MSG_WAITALL);
  144.  
  145.     if(size == -1){
  146.         printerror("recieving data from server");
  147.     }else{
  148.         buff[size] = '';
  149.  
  150.         puts(buff);
  151.     }
  152.  
  153.     shutdown(sfd, SHUT_RDWR);
  154.  
  155.     return NULL;
  156. }
  157.  
  158.  
This is C code, but I thought, "If I get this working, encapsulating in classes will be easy". The problem is that this code works fine only the first run; afterwards, it cannot resolve the IP address. Which could be the reason?
Oct 30 '06 #1
2 24260
I discovered that changing the port number and recompiling allows for another succesful run (only once, like before). Therefore, it seems to me that ports are not freed after the program finishes. How can I do that?
Oct 31 '06 #2
Well, I figured it out myself: Even if you close a socket correctly, it takes a maximum of 60 seconds for it to be freed: I ran the first time OK; then I waited a minute, ran again and had no problems. So that's it, I hope this helps someone.
Nov 1 '06 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Jon Perez | last post by:
Running the following under Linux creates 3 processes instead of 2. Once the started thread exits, 2 processes still remain. Why? import thread from thread import start_new_thread def...
1
by: Josef Meile | last post by:
Hi, I'm trying to do a simple link checking for python 2.1.3 (compiled from source on linux), but it fails when I use an invalid ssl url. For example: I have zope without ssl running on port...
0
by: Al Tobey | last post by:
I was building perl 5.8.2 on RedHat Enterprise Linux 3.0 (AS) today and noticed that it included in it's ccflags "-DTHREADS_HAVE_PIDS." I am building with -Dusethreads. With newer Linux...
2
by: shyamal | last post by:
I want to display memory content using C++ on LINUX. For example, the user may ask to display 256 bytes from 0x1000ff00. The problem is , if any location is invalid, the program will coredump...
9
by: nan.li.g | last post by:
Hello, all, I have an interesting problem about stl map and pthread on Linux and g++. The source code is as follows. //mt_map_test.cpp #include <string> #include <map> #include <unistd.h>...
1
by: lineak | last post by:
Hi all, does anyone know how to compile with gcc using a different library from pthreads (for example libc clone() call)? if I type gcc -v I get: Reading specs from...
15
by: kernel.lover | last post by:
Hello, i want to know to have multiple clients connects to same server program does following is correct code #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include...
2
by: Stressed Out Developer | last post by:
We have an application that has a 200 count loop that does the following: ' Each time thru the loop we pass the next IP Address is a range (aka 192.168.4.50 thru 192.168.4.254) Try If...
7
by: Sourav | last post by:
Hi, I am new to linux and was writing a program that uses linux POSIX Threads. I had to show some activity on the screen while some files will be copied in the background. I thought of implementing...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.