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: -
-
#include <stdlib.h>
-
#include <stdio.h>
-
#include <string.h>
-
#include <errno.h>
-
#include <netdb.h>
-
#include <signal.h>
-
#include <fcntl.h>
-
#include <netinet/ip.h>
-
#include <pthread.h>
-
-
struct sockaddr_in getipa(const char*, int);
-
void printerror(const char*);
-
-
void* runclient(void*);
-
void* runserver(void*);
-
-
int main(){
-
pthread_t server;
-
pthread_t client;
-
-
if(pthread_create(&server, NULL, runserver, NULL) != 0){
-
puts("Could not create server thread");
-
-
return EXIT_FAILURE;
-
}
-
-
if(pthread_create(&client, NULL, runclient, NULL) != 0){
-
puts("Could not create client thread");
-
-
return EXIT_FAILURE;
-
}
-
-
pthread_join(server, NULL);
-
pthread_join(client, NULL);
-
-
return EXIT_SUCCESS;
-
}
-
-
struct sockaddr_in getipa(const char* hostname, int port){
-
struct sockaddr_in ipa;
-
ipa.sin_family = AF_INET;
-
ipa.sin_port = htons(port);
-
-
struct hostent* localhost = gethostbyname(hostname);
-
if(!localhost){
-
printerror("resolveing localhost");
-
-
return ipa;
-
}
-
-
char* addr = localhost->h_addr_list[0];
-
memcpy(&ipa.sin_addr.s_addr, addr, sizeof addr);
-
-
return ipa;
-
}
-
-
void printerror(const char* action){
-
int errnum = errno;
-
errno = 0;
-
-
if(errnum > 0){
-
printf("An error occured while %s.nError code: %inError description: %sn",
-
action, errnum, strerror(errnum));
-
}else if(h_errno > 0){
-
printf("An error occured while %s.nError code: %inError description: %sn",
-
action, h_errno, hstrerror(h_errno));
-
-
h_errno = 0;
-
}else{
-
printf("An error occured while %s.n There is no error data.n", action);
-
}
-
}
-
-
void* runserver(void* context){
-
struct protoent* tcp;
-
tcp = getprotobyname("tcp");
-
-
int sfd = socket(PF_INET, SOCK_STREAM, tcp->p_proto);
-
if(sfd == -1){
-
printerror("createing a tcp socket");
-
-
return NULL;
-
}
-
-
struct sockaddr_in isa = getipa("localhost", 1025);
-
-
if(bind(sfd, (struct sockaddr*)&isa, sizeof isa) == -1){
-
printerror("binding socket to IP address");
-
-
return NULL;
-
}
-
-
if(listen(sfd, 1) == -1){
-
printerror("setting socket to listen");
-
-
return NULL;
-
}
-
-
int cfd = accept(sfd, NULL, NULL);
-
-
if(cfd == -1){
-
if(errno == EAGAIN || errno == EWOULDBLOCK){
-
puts("SIGIO recieved for listen socket, but don't know why.");
-
}else{
-
printerror("accepting a connection");
-
-
return NULL;
-
}
-
}
-
-
char msg[] = "Message to be sent";
-
-
if(send(cfd, (void*) msg, sizeof msg, MSG_NOSIGNAL) == -1){
-
printerror("sending message to client");
-
}
-
-
shutdown(cfd, SHUT_RDWR);
-
-
return NULL;
-
}
-
-
void* runclient(void* context){
-
struct protoent* tcp;
-
tcp = getprotobyname("tcp");
-
-
int sfd = socket(PF_INET, SOCK_STREAM, tcp->p_proto);
-
if(sfd == -1){
-
printerror("createing a tcp socket");
-
-
return NULL;
-
}
-
-
struct sockaddr_in isa = getipa("localhost", 1025);
-
-
if(connect(sfd, (struct sockaddr*)&isa, sizeof isa) == -1){
-
printerror("connecting to server");
-
-
return NULL;
-
}
-
-
char buff[255];
-
ssize_t size = recv(sfd, (void*)buff, sizeof buff, MSG_WAITALL);
-
-
if(size == -1){
-
printerror("recieving data from server");
-
}else{
-
buff[size] = '';
-
-
puts(buff);
-
}
-
-
shutdown(sfd, SHUT_RDWR);
-
-
return NULL;
-
}
-
-
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?
2 24283
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?
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.
Sign in to post your reply or Sign up for a free account.
Similar topics |
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"
|
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
|
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.
...
|
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...
|
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>
| |
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...
|
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>
|
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
|
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;
|
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...
|
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,...
| |
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...
|
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...
|
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,...
|
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...
|
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();...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |