473,796 Members | 2,590 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Linux Sockets and POSIX threads example

34 New Member
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 24283
dariophoenix
34 New Member
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
dariophoenix
34 New Member
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
2719
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 newthread(): print "child"
1
2117
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 8080, if I do this on the browser's address bar: https://my_ip:8080 --> The https is intentional mozilla on linux and IE on windows, take a long time till a timeout
0
2012
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 distributions using the Native Posix Threading Layer (NPTL), this isn't entirely true anymore and is AFAIK unsupported (using a pid to signal/identify threads). I removed it from my config.sh script and ran Configure -der. make test runs just fine. ...
2
6898
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 because of attempt to access invalid memory.I understand that in Windows OS there is a function that tells if a memory location is valid or invalid. Is there a similar function in Linux? How does gdb display memory content? I will appreciate a...
9
8000
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> #include <sys/types.h>
1
2487
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 /usr/lib/gcc-lib/i386-redhat-linux/3.2.2/specs Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --disable-checking --with-system-zlib --enable-__cxa_atexit --host=i386-redhat-linux Thread...
15
2491
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 <netinet/in.h> #include <signal.h> #include <unistd.h>
2
2361
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 mUIO_Threads(i) Is Nothing Then mUIO_Threads(i) = New System.Threading.Thread(AddressOf mUIO_DAQ(i).InitDAQ) mUIO_Threads(i).Name = mUIO_DAQ(i).UIO_IPAddr mUIO_Threads(i).IsBackground = False
7
2048
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 it using threads and to just test the algorithm I wrote the following, #include <stdio.h> #include <pthread.h> #include <unistd.h> int running=1;
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9533
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10461
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10239
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10190
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10019
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6796
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3736
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2928
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.