Could you recommend some guides about Epoll on Linux [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
I need to know about Epoll On linux System.
Could you recommend manual or guides about epoll library?
need more detailed guides. it's better to have some examples.
help me. and Thank you for reading.

Here's an introduction to Epoll, a pretty basic tutorial: http://blog.kovyrin.net/2006/04/13/epoll-asynchronous-network-programming/
A more complete example can be found here: https://banu.com/blog/2/how-to-use-epoll-a-complete-example-in-c/
Also, the man pages

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#define PORT 1500
#define MAX_CON (1200)
static struct epoll_event *events;
int main(int argc, char *argv[])
{
fd_set master;
fd_set read_fds;
struct sockaddr_in serveraddr;
struct sockaddr_in clientaddr;
int fdmax;
int listener;
int newfd;
char buf[1024];
int nbytes;
int addrlen;
int yes;
int epfd = -1;
int res = -1;
struct epoll_event ev;
int i=0;
int index = 0;
int client_fd = -1;
int SnumOfConnection = 0;
time_t Sstart, Send;
if((listener = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("Server-socket() error lol!");
exit(1);
}
if(setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
{
perror("Server-setsockopt() error lol!");
exit(1);
}
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = INADDR_ANY;
serveraddr.sin_port = htons(PORT);
memset(&(serveraddr.sin_zero), '\0', 8);
if(bind(listener, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) == -1)
{
perror("Server-bind() error lol!");
exit(1);
}
if(listen(listener, 10) == -1)
{
perror("Server-listen() error lol!");
exit(1);
}
fdmax = listener; /* so far, it's this one*/
events = calloc(MAX_CON, sizeof(struct epoll_event));
if ((epfd = epoll_create(MAX_CON)) == -1) {
perror("epoll_create");
exit(1);
}
ev.events = EPOLLIN;
ev.data.fd = fdmax;
if (epoll_ctl(epfd, EPOLL_CTL_ADD, fdmax, &ev) < 0) {
perror("epoll_ctl");
exit(1);
}
//time(&start);
for(;;)
{
res = epoll_wait(epfd, events, MAX_CON, -1);
client_fd = events[index].data.fd;
for (index = 0; index < MAX_CON; index++) {
if(client_fd == listener)
{
addrlen = sizeof(clientaddr);
if((newfd = accept(listener, (struct sockaddr *)&clientaddr, &addrlen)) == -1)
{
perror("Server-accept() error lol!");
}
else
{
// printf("Server-accept() is OK...\n");
ev.events = EPOLLIN;
ev.data.fd = newfd;
if (epoll_ctl(epfd, EPOLL_CTL_ADD, newfd, &ev) < 0) {
perror("epoll_ctl");
exit(1);
}
}
break;
}
else
{
if (events[index].events & EPOLLHUP)
{
if (epoll_ctl(epfd, EPOLL_CTL_DEL, client_fd, &ev) < 0) {
perror("epoll_ctl");
}
close(client_fd);
break;
}
if (events[index].events & EPOLLIN) {
if((nbytes = recv(client_fd, buf, sizeof(buf), 0)) <= 0)
{
if(nbytes == 0) {
// printf("socket %d hung up\n", client_fd);
}
else {
printf("recv() error lol! %d", client_fd);
perror("");
}
if (epoll_ctl(epfd, EPOLL_CTL_DEL, client_fd, &ev) < 0) {
perror("epoll_ctl");
}
close(client_fd);
}
else
{
if(send(client_fd, buf, nbytes, 0) == -1)
perror("send() error lol!");
}
break;
}
}
}
}
return 0;
}
I wrote this program for testing and I was able to connect more than 80k connections and I find average system load only to 0.27%.

Related

accept socket errno 9 c++

New to socket programming, trying to implement a TCP server, but accept() returns -1 and errno = 9 (bad file descriptor). The problem arose after I introduced the accept() function in the freertos task. I really don’t understand what the problem is here, because before this my action everything worked, but I need to use the task.
#include "TCP.hpp"
#include <iostream>
#include <cmath>
#include <cerrno>
#include <cstring>
#include <clocale>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "freertos/queue.h"
#include "lwip/err.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include <lwip/netdb.h>
#include "ping/ping_sock.h"
#include "errno.h"
static const char *TAG = "TCP";
QueueHandle_t TCP::xQueue1 = NULL;
ip_addr_t TCP::target_addr;
int TCP::ip_protocol;
int TCP::listen_sock;
sockaddr_in TCP::servaddr;
sockaddr_in TCP::cliaddr;
char TCP::addr_str[128];
char TCP::buf[128];
int TCP::sock;
TCP::Clbk_t TCP::clbk_tcp_recv = nullptr;
sockaddr_storage TCP::source_addr;
typedef struct
{
int len;
void * dataPtr;
}message;
void TCP::tcp_set_Clbk(Clbk_t clbk)
{
clbk_tcp_recv = clbk;
}
void TCP::tcp_create_server(sa_family_t serv_family, in_addr_t serv_addr, in_port_t serv_port)
{
int opt = 1;
struct sockaddr_in6 *servaddrPtr;
if (serv_family == AF_INET){
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_len = 24;
servaddr.sin_family = serv_family;
servaddr.sin_addr.s_addr = serv_addr;
servaddr.sin_port = htons(serv_port);
ip_protocol = IPPROTO_IP;
} else if (serv_family == AF_INET6){
servaddrPtr = (struct sockaddr_in6 *)&servaddr;
servaddrPtr->sin6_len = 24;
servaddrPtr->sin6_family = serv_family;
servaddrPtr->sin6_port = htons(serv_port);
ip_protocol = IPPROTO_IPV6;
}
ESP_LOGI(TAG, "Create socket...\n");
if ((listen_sock = socket(serv_family, SOCK_STREAM, ip_protocol)) < 0) {
ESP_LOGE(TAG, "socket not created\n");
}
setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
ESP_LOGI(TAG, "Socket created");
int err = bind(listen_sock, (struct sockaddr *)&servaddr, sizeof(servaddr));
if (err != 0) {
ESP_LOGE(TAG, "Socket unable to bind errno %d", errno);
ESP_LOGE(TAG, "IPPROTO: %d", serv_family);
goto CLEAN_UP;
}
ESP_LOGI(TAG, "Socket bound, port %d", serv_port);
err = listen(listen_sock, 1);
if (err != 0) {
ESP_LOGE(TAG, "Error occurred during listen: errno %d", errno);
goto CLEAN_UP;
}
ESP_LOGI(TAG, "Soccket listening . . .");
xTaskCreate(tcp_listening_task, "tcp_listening_task", 4096, nullptr, 5, nullptr);
CLEAN_UP:
close(listen_sock);
}
void TCP::tcp_listening_task(void *arg)
{
int keepAlive = 1;
socklen_t addr_len = sizeof(source_addr);
ESP_LOGI(TAG, "Socket %d ",listen_sock);
for (;;) {
sock = accept(listen_sock, (struct sockaddr *)&source_addr, &addr_len);
ESP_LOGI(TAG, "Socket %d ",sock);
if (sock < 0) {
ESP_LOGE(TAG, "Unable to accept connection: errno %d", errno);
}
if (sock > 0) {
setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &keepAlive, sizeof(int));
if (source_addr.ss_family == PF_INET) {
inet_ntoa_r(((struct sockaddr_in *)&source_addr)->sin_addr, addr_str, sizeof(addr_str) - 1);
}
else if (source_addr.ss_family == PF_INET6) {
inet6_ntoa_r(((struct sockaddr_in *)&source_addr)->sin_addr, addr_str, sizeof(addr_str) - 1);
}
ESP_LOGI(TAG, "Socket %d accepted ip address: %s",sock, addr_str);
xTaskCreate(tcp_task_recv, "tcp_task_recv", 4096, nullptr, 5, nullptr);
}
}
}
void TCP::tcp_task_recv(void *arg)
{
int n;
int number_receiving = 0;
struct timeval tv;
tv.tv_sec = 1;
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,(struct timeval *)&tv,sizeof(struct timeval));
ESP_LOGI(TAG,"server waiting message");
for (;;) {
n = recv(sock, (char *)buf, sizeof(buf), 0);
if (n < 0) {
ESP_LOGE(TAG, "Error occurred during receiving: errno %d", errno);
number_receiving++;
if (number_receiving == 10) {
number_receiving = 0;
}
}
else if (n == 0) {
ESP_LOGW(TAG, "Connection closed");
number_receiving = 0;
}
else {
if (clbk_tcp_recv != nullptr) clbk_tcp_recv(buf, n, (struct sockaddr *)&source_addr);
number_receiving = 0;
}
}
}
void TCP::tcp_sendd(void *data, uint32_t length)
{
static message msg;
xQueue1 = xQueueCreate(10, sizeof(message));
xTaskCreate(tcp_task_send, "udp_task_send", 4096, nullptr, 5, nullptr);
if(sock < 0){
ESP_LOGE(TAG, "Unable to accept connection: errno %d", errno);
return;
}
if(xQueue1 == NULL){
ESP_LOGE(TAG, "queue is null");
return;
}
msg.dataPtr = data;
msg.len = length;
xQueueSend(xQueue1, (void *)&msg, portMAX_DELAY);
}
void TCP::tcp_task_send(void *arg)
{
message pxRxedMessage;
for(;;)
{
xQueueReceive(xQueue1, (void *)&pxRxedMessage, portMAX_DELAY);
int err = send(sock, pxRxedMessage.dataPtr, pxRxedMessage.len, 0);
if (err < 0){
ESP_LOGE(TAG, "Error occurred during sending: errno %d", errno);
}
}
}
I tried to look for information on this issue, but since. I'm also new to c++ programming, nothing worked out
You should be passing the listen_sock as the arg parameter to tcp_listening_task(), rather than using a static class member, eg:
int listen_sock = socket(...);
...
xTaskCreate(tcp_listening_task, "tcp_listening_task", 4096, reinterpret_cast<void*>(listen_sock), 5, nullptr);
...
void TCP::tcp_listening_task(void *arg)
{
int listen_sock = reinterpret_cast<int>(arg);
...
close(listen_sock);
}
And especially the same with sock and tcp_task_recv() too, since your server is designed to handle multiple clients being connected simultaneously, which you can't handle with a single static sock variable:
int sock = accept(...);
...
xTaskCreate(tcp_task_recv, "tcp_task_recv", 4096, reinterpret_cast<void*>(sock), 5, nullptr);
...
void TCP::tcp_task_recv(void *arg)
{
int sock = reinterpret_cast<int>(arg);
...
close(sock);
}

Socket accept invalid argument (c++)

I am trying to create a web-server which will accept requests and commands from sockets (in different ports). I have some demo code for simple socket communication, which compiles and runs as expected, but when I run mine (written with demo as a reference, that is why there are some printf's) accept() fails with :
"invalid argument" as error. I can not find what is wrong.
Any suggestion/correction is appreciated.
Here is my code:
#include <iostream>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <cstring>
#include <cstdlib>
#include <cstddef>
void perror_exit(char *message);
void thread_run();
int main(int argc, char const *argv[])
{
int i, filepos, serving_port=0, command_port=0, thread_num=0;
char *root_dir = (char *)malloc(sizeof(char *));
int serv_sock=0, command_sock=0, new_sock_c, new_sock_s=0;
struct sockaddr_in server,commands;
struct sockaddr_in server_client,commands_client;
struct sockaddr *serverptr=(struct sockaddr *)&server;
struct sockaddr *commandsptr=(struct sockaddr *)&commands;
struct sockaddr *server_clientptr=(struct sockaddr *)&server_client;
struct sockaddr *commands_clientptr=(struct sockaddr *)&commands_client;
socklen_t clientlen_s, clientlen_c;
struct hostent *rem_s, *rem_c;
socklen_t clientlen;
if(argc != 9){
perror("Wrong number of arguments, webServer");
exit(1);
}else{
for (i=0;i<argc;i++){
if (strcmp(argv[i],"-p") == 0){
serving_port = atoi(argv[i+1]);
}
}
for (i=0;i<argc;i++){
if (strcmp(argv[i],"-c") == 0){
command_port = atoi(argv[i+1]);
}
}
for (i=0;i<argc;i++){
if (strcmp(argv[i],"-t") == 0){
thread_num = atoi(argv[i+1]);
}
}
for (i=0;i<argc;i++){
if (strcmp(argv[i],"-d") == 0){
filepos = i+1;
strncpy(root_dir, argv[i+1], strlen(argv[i+1])+1); // +1 to get "\n" too, without +1 seg fault appears
}
}
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(serving_port);
commands.sin_family = AF_INET;
commands.sin_addr.s_addr = htonl(INADDR_ANY);
commands.sin_port = htons(command_port);
if ((serv_sock = socket(AF_INET,SOCK_STREAM,0)) == -1)
{
perror_exit("Failed to create serving socket");
// return -1;
}
if ((command_sock = socket(AF_INET,SOCK_STREAM,0)) == -1)
{
perror_exit("Failed to create command socket");
// return -1;
}
if (bind(serv_sock, serverptr, sizeof(server)) < 0)
perror_exit("bind");
printf("Listening for connections to port %d\n", serving_port);
if (bind(command_sock, commandsptr, sizeof(server)) < 0)
perror_exit("bind");
printf("Listening for commands to port %d\n", command_port);
while(true)
{
clientlen_s = sizeof(server_client);
clientlen_c = sizeof(commands_client);
if ((new_sock_s = accept(serv_sock, server_clientptr, &clientlen_s)) < 0)
perror_exit("accept (server)");
if ((new_sock_c = accept(command_sock, commands_clientptr, &clientlen_c)) < 0)
perror_exit("accept (commands)");
if ((rem_s = gethostbyaddr((char *) &server_client.sin_addr.s_addr, sizeof(server_client.sin_addr.s_addr), server_client.sin_family)) == NULL) {
herror("gethostbyaddr"); exit(1);
}
printf("Accepted serving connection from %s\n", rem_s->h_name);
if ((rem_c = gethostbyaddr((char *) &commands_client.sin_addr.s_addr, sizeof(commands_client.sin_addr.s_addr), commands_client.sin_family)) == NULL) {
herror("gethostbyaddr"); exit(1);
}
printf("Accepted command connection from %s\n", rem_c->h_name);
}
/* code */
return 0;
}
void perror_exit(char *message)
{
perror(message);
exit(EXIT_FAILURE);
}
void thread_run()
{
}
Before calling accept, you should call listen.
From accept manual :
EINVAL Socket is not listening for connections, or addrlen is invalid
(e.g., is negative).
You should add before the loop:
listen(serv_sock,5);
listen(command_sock,5);
However in order to not block in the accept call if no connection is pending, you should consider to use select or poll.
This will allow to check if connection is pending before calling accept

C++ - Thread for socket server [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to implement a server, which runs in his own thread.
Later, the server should work together with another thread.
Is that even possible?
My current attempt to implement this:
main
#include "EtherServer.h"
int main(int argc, char *argv[])
{
EtherServer* es = new EtherServer();
es->init();
return 0;
}
Server.h
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
#ifndef ETHERSERVER_H_
#define ETHERSERVER_H_
class EtherServer
{
public:
bool init();
static void* runServer(void *arg);
static void sigchld_handler(int s);
static void* get_in_addr(struct sockaddr *sa);
static int s_sockfd;
private:
};
#endif /* ETHERSERVER_H_ */
Server.cpp
#include "EtherServer.h"
#define PORT "31107" // the port users will be connecting to
#define BACKLOG 10 // how many pending connections queue will hold
int EtherServer::s_sockfd = 0;
void EtherServer::sigchld_handler(int s)
{
// waitpid() might overwrite errno, so we save and restore it:
int saved_errno = errno;
while(waitpid(-1, NULL, WNOHANG) > 0);
errno = saved_errno;
}
// get sockaddr, IPv4 or IPv6:
void* EtherServer::get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
}
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
bool EtherServer::init()
{
int rv;
int yes=1;
struct addrinfo hints, *servinfo, *p;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next)
{
if ((EtherServer::s_sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("server: socket");
continue;
}
if (setsockopt(EtherServer::s_sockfd, SOL_SOCKET, SO_REUSEADDR, yes,
sizeof(int)) == -1)
{
perror("setsockopt");
exit(1);
}
if (bind(EtherServer::s_sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
close(EtherServer::s_sockfd);
perror("server: bind");
continue;
}
break;
}
freeaddrinfo(servinfo); // all done with this structure
if (p == NULL) {
fprintf(stderr, "server: failed to bind\n");
exit(1);
}
if (listen(EtherServer::s_sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
struct sigaction sa;
sa.sa_handler = EtherServer::sigchld_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
perror("sigaction");
exit(1);
}
pthread_attr_t attr_baseb;
(void)pthread_attr_init(&attr_baseb);
(void)pthread_attr_setdetachstate(&attr_baseb, PTHREAD_CREATE_DETACHED);
(void)pthread_create(NULL, &attr_baseb, &runServer, (void *)this);
}
void* EtherServer::runServer(void *arg)
{
int new_fd; // listen on sock_fd, new connection on new_fd
//struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage their_addr; // connector's address information
socklen_t sin_size;
char s[INET6_ADDRSTRLEN];
printf("server: waiting for connections...\n");
while(1) { // main accept() loop
sin_size = sizeof their_addr;
sleep(1);
new_fd = accept(EtherServer::s_sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family, EtherServer::get_in_addr((struct sockaddr *)&their_addr), s, sizeof s);
printf("server: got connection from %s\n", s);
if (!fork()) { // this is the child process
int n;
char buffer[256];
bzero(buffer, 256);
close(EtherServer::s_sockfd); // child doesn't need the listener
while (n = read(new_fd, buffer, 255) > 0)
{
if (send(new_fd, buffer, 255, 0) == -1)
perror("send");
}
close(new_fd);
exit(0);
sleep(1);
}
close(new_fd); // parent doesn't need this
}
}
Your thread runs as a child of main(). When you return from main its child threads are killed, too.
Rather than return, main will have to perform some wait operation of its own, so that it will only exit cleanly when all child threads have completed.

Executing linux c++ program in windows [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have seen that some of the c++ header file in windows has alternative in linux. Here I have created socket program and one more string processing program in linux-c++.
Is it possible to modify such that same code works in both windows as well in linux?
code 1:
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <netinet/in.h>
#include <resolv.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
//#include <sstream.h>
#include <pthread.h>
#include <iostream>
#include <sstream>
#include <cstdio>
#include <vector>
#include <map>
#include "dictionary_exclude.h"
#pragma GCC diagnostic ignored "-Wwrite-strings"
void *SocketHandler(void *);
int main(int argv, char **argc)
{
int host_port = 1103;
char buf[20];
int k;
struct sockaddr_in my_addr;
int hsock;
int *p_int;
int err;
socklen_t addr_size = 0;
int *csock;
sockaddr_in sadr;
pthread_t thread_id = 0;
hsock = socket(AF_INET, SOCK_STREAM, 0);
if (hsock == -1) {
printf("Error initializing socket %dn", errno);
goto FINISH;
}
p_int = (int *) malloc(sizeof(int));
*p_int = 1;
if ((setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char *) p_int, sizeof(int)) == -1) || (setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char *) p_int, sizeof(int)) == -1)) {
printf("Error setting options %dn", errno);
free(p_int);
goto FINISH;
}
free(p_int);
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(host_port);
memset(&(my_addr.sin_zero), 0, 8);
my_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(hsock, (sockaddr *) & my_addr, sizeof(my_addr)) == -1) {
fprintf(stderr, "Error binding to socket, make sure nothing else is listening on this port %dn", errno);
goto FINISH;
}
if (listen(hsock, 10) == -1) {
fprintf(stderr, "Error listening %dn", errno);
goto FINISH;
}
//Now lets do the server stuff
addr_size = sizeof(sockaddr_in);
while (true) {
printf("waiting for a connectionn\n");
csock = (int *) malloc(sizeof(int));
if ((*csock = accept(hsock, (sockaddr *) & sadr, &addr_size)) != -1) {
printf("---------------------nReceived connection from %s\n", inet_ntoa(sadr.sin_addr));
pthread_create(&thread_id, 0, &SocketHandler, (void *) csock); //Pthread to manage requests from multiple clients
pthread_detach(thread_id);
} else {
fprintf(stderr, "Error accepting %dn", errno);
}
}
FINISH:
;
}
void *SocketHandler(void *lp)
{
int ar[10];
int result=0;
int *csock = (int *) lp;
char buf[20];
int k;
const unsigned int MAX_BUF_LENGTH = 4096;
std::vector<char> buffer(MAX_BUF_LENGTH);
std::string input;
int bytesReceived = 0;
//char buffer[1024];
int buffer_len = 1024;
int bytecount;
int i = 0;
std::string current;
std::vector<std::string> sentences;
if ((bytecount = recv(*csock, (char*) input.c_str(), input.length(), 0)) == -1) {
fprintf(stderr, "Error receiving data %d \n", errno);
goto FINISH;
}
do {
bytesReceived = recv(*csock, buffer.data(), buffer.size(), 0);
// append string from buffer.
if ( bytesReceived == -1 )
{
fprintf(stderr, "Error receiving data %d \n", errno);
goto FINISH;
}
else
input.append( buffer.cbegin(), buffer.cend() );
} while ( bytesReceived == MAX_BUF_LENGTH );
while(i < input.length())
{
current += input[i];
if(input[i] == '"')
{
int j = i + 1;
while( j < input.length() && input[j] != '"')
{
current += input[j];
j ++;
}
current += input[j];
i = j + 1;
}
if(input[i] == '.' || input [i] == '!' || input[i] == '?')
{
sentences.push_back(current);
current = "";
}
i ++;
}
for(i =0; i<sentences.size(); i++)
{
std::cout << i << " -> " << sentences[i] << std::endl;
}
if ((bytecount = send(*csock, (char *)ar, i *sizeof(int), 0)) == -1) { // Here we cant send lenth-1. It consider exact
fprintf(stderr, "Error sending data %d\n", errno);
goto FINISH;
}
FINISH:
free(csock);
return 0;
}
code 2:
#include<stdio.h>
#include<string.h>
#include "client.h"
int main(int argc, char *argv[] )
{
const char *buffer;
const char *ch;
std::string input = argv[1];
int ar[2];
printf("Client : \n");
if ( argc != 2 ) /* argc should be 2 for correct execution */
{
printf( "\n%s filename\n", argv[0] );
}
else
{
ch=client(input);
ar[0]=((int*)ch)[0];
ar[1]=((int*)ch)[1];
}
printf("\n #ar[0]=%d;ar[1]=%d# \n",ar[0],ar[1]);
return ar[1];
}
header file
#include <iostream>
#ifndef client_h__
#define client_h__
extern char *client(std::string string_input);
#endif
Sockets and threads do not have a standard API used by both Windows and Linux. Although they are somewhat similar, you will have to modify your code in order to get it to work for windows.

how to establish sip session in .c programming between client and server

this is client server application I want to establish SIP (session initiation protocol) between client and server.
So please anyone guide me how can I do this.
server.c:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <netinet/tcp.h>
#define MYPORT 3490 // the port users will be connecting to
#define BACKLOG 10 // how many pending connections queue will hold
#define MAXDATASIZE 100
void str_server(int);
void sigchld_handler(int s)
{
while(waitpid(-1, NULL, WNOHANG) > 0);
}
int main(void)
{
int sockfd, numbytes,new_fd, optlen; // listen on sock_fd, new connection on new_fd
struct sockaddr_in my_addr; // my address information
struct sockaddr_in their_addr; // connector's address information
struct tcp_info info;
socklen_t sin_size;
struct sigaction sa;
char buf[MAXDATASIZE];
int yes=1;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}
my_addr.sin_family = AF_INET; // host byte order
my_addr.sin_port = htons(MYPORT); // short, network byte order
my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP
memset(my_addr.sin_zero, '\0', sizeof my_addr.sin_zero);
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof my_addr) == -1) {
perror("bind");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
sa.sa_handler = sigchld_handler; // reap all dead processes
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sa, NULL) == -1) {
perror("sigaction");
exit(1);
}
while(1) { // main accept() loop
sin_size = sizeof their_addr;
getchar();
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, \
&sin_size)) == -1) {
perror("accept");
continue;
}
printf("server: got connection from %s\n", \
inet_ntoa(their_addr.sin_addr));
if (!fork()) { // this is the child process
close(sockfd); // child doesn't need the listener
if ((numbytes=recv(new_fd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
exit(1);
}
buf[numbytes] = '\0';
printf("Received From Client: %s\n",buf);
str_server(sockfd);
FILE *fp = fopen( "adventure.mpg", "rb" );
//if(!fork())
// execlp("gedit", "gedit", "SIPFILE.txt", NULL);
//system("popen /home/umair/Documents/CurrentData/SIPFILE.txt");
//ShellExecute(GetDesktopWindow(), "open","ls /home/umair/Documents
/CurrentData/SIPFILE.txt",NULL, NULL, SW_SHOW);
if (send(new_fd, "Hello, world!\n", 14, 0) == -1)
perror("send");
close(new_fd);
exit(0);
}
close(new_fd); // parent doesn't need this
}
return 0;
}
void str_server(int sock)
{
char buf[1025];
const char* filename = "test.text";
FILE *file = fopen(filename, "rb");
if (!file)
{
printf("Can't open file for reading");
return;
}
while (!feof(file))
{
int rval = fread(buf, 1, sizeof(buf), file);
if (rval < 1)
{
printf("Can't read from file");
fclose(file);
return;
}
int off = 0;
do
{
int sent = send(sock, &buf[off], rval - off, 0);
if (sent < 1)
{
// if the socket is non-blocking, then check
// the socket error for WSAEWOULDBLOCK/EAGAIN
// (depending on platform) and if true then
// use select() to wait for a small period of
// time to see if the socket becomes writable
// again before failing the transfer...
printf("Can't write to socket");
fclose(file);
return;
}
off += sent;
}
while (off < rval);
}
fclose(file);
}
//client.c :
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netinet/tcp.h>
#define PORT 3490 // the port client will be connecting to
#define MAXDATASIZE 100 // max number of bytes we can get at once
void RecvFile(int , const char* );
FILE *filename;
int main(int argc, char *argv[])
{
int sockfd, numbytes, optlen;
char buf[MAXDATASIZE];
char *message;
struct hostent *he;
struct tcp_info info;
struct sockaddr_in their_addr; // connector's address information
if (argc != 2) {
fprintf(stderr,"usage: client hostname\n");
exit(1);
}
if ((he=gethostbyname(argv[1])) == NULL) { // get the host info
herror("gethostbyname");
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
their_addr.sin_family = AF_INET; // host byte order
their_addr.sin_port = htons(PORT); // short, network byte order
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);
if (connect(sockfd, (struct sockaddr *)&their_addr,
sizeof their_addr) == -1) {
perror("connect");
exit(1);
}
printf("connect successfull\n");
/* if (send(sockfd, "Hello, world!\n", 14, 0) == -1)
perror("send");
printf("send successfull\n");
*/
message = "GET /?st=1 HTTP/1.1\r\nHost: www.msn.com\r\n\r\n";
if( send(sockfd , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
puts("Data Send\n");
RecvFile(sockfd , message);
optlen = sizeof(info);
if ((numbytes=recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
exit(1);
}
buf[numbytes] = '\0';
printf("Received: %s\n",buf);
close(sockfd);
return 0;
}
void RecvFile(int sock, const char* filename)
{
int rval;
char buf[0x1000];
FILE *file = fopen(filename, "wb");
if (!file)
{
printf("Can't open file for writing");
return;
}
do
{
rval = recv(sock, buf, sizeof(buf), 0);
if (rval < 0)
{
// if the socket is non-blocking, then check
// the socket error for WSAEWOULDBLOCK/EAGAIN
// (depending on platform) and if true then
// use select() to wait for a small period of
// time to see if the socket becomes readable
// again before failing the transfer...
printf("Can't read from socket");
fclose(file);
return;
}
if (rval == 0)
break;
int off = 0;
do
{
int written = fwrite(&buf[off], 1, rval - off, file);
if (written < 1)
{
printf("Can't write to file");
fclose(file);
return;
}
off += written;
}
while (off < rval);
}
while (!feof(file));
fclose(file);
}
Any Suggestion?
I am not sure what you are trying to do with SIP, but the code snippet you've provided shows only establishing a TCP/IP connection. If you intend to do a SIP server-client application, I suggest that you look for a library to help you along the way.
One that I know of that is very complete is called Sofia SIP:
http://sofia-sip.sourceforge.net/
It's written by Nokia for Linux in C language.
Source code is available here: http://gitorious.org/sofia-sip/sofia-sip/trees/master
(Older http://sourceforge.net/p/sofia-sip/git/ci/master/tree/)
you can learn about sipp scenarios and message passing through this utility and its documentation.