Hello friends;
I want to put my socket programming example of how it can support multiple ports.
I want to make the process more requests from distributing particles to create non-blocking structure
ports support ports defined variable.
Code:
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "errno.h"
#include "string.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "arpa/inet.h"
#include "sys/types.h"
#define BUFFSIZE 1024
#define SOCKET_ERROR -1
int listenfd = 0;
int connection = 0;
int ports[] = { 9000,9001,9002,9003,9004,9005 };
struct sockaddr_in httpd;
char sendBuff[BUFFSIZE];
char fromBuff[BUFFSIZE];
void syslog(int type,char * msg)
{
// sistem hata(sı) ve bilgi mesajları
switch(type)
{
case 1 : printf("Failed to listen (%s)\n",msg);
case 2 : printf("There are a new user connection (%s)\n",msg);
}
}
int main()
{
listenfd = socket(AF_INET,SOCK_STREAM,0);
memset(&httpd,'0',sizeof(httpd));
memset(sendBuff,'0',sizeof(sendBuff));
// socket ayarlarımızı yapıyoruz
httpd.sin_family = AF_INET;
httpd.sin_addr.s_addr = htonl(INADDR_ANY);
httpd.sin_port = htons(ports[1]);
bind(listenfd,(struct sockaddr*)&httpd,sizeof(httpd));
// bağlantı durumunu kontrol ediyoruz.
if(listen(listenfd,10) == SOCKET_ERROR)
{
syslog(1,NULL);
}
while(1)
{
connection = accept(listenfd,(struct sockaddr*)NULL,NULL);
// HTTP başlıklarını yazıyoruz
const char * header =
(
"HTTP/1.0 200 OK\n"
"Content-Type: text/html; charset=utf-8\n\n"
"Hello World"
);
// HTTP başlıklarını ve html verilerini gönderiyoruz
strcpy(sendBuff,header);
write(connection,sendBuff,strlen(sendBuff));
// HTTP üzerinden gelen başlıkları ve verileri alıyoruz
read(connection,fromBuff,sizeof(fromBuff));
puts(fromBuff);
// uyku moduna geçiriyoruz
shutdown(connection,SHUT_RDWR);
close(connection);
}
return 0;
}