
Untitled
By: a guest on
Aug 2nd, 2012 | syntax:
C | size: 2.02 KB | hits: 13 | expires: Never
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <linux/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/wait.h>
#define PORT 12345
int main(void)
{
socklen_t inputlength;
fd_set rfds;
struct timeval tv;
int clilen;
int tcp_sockfd,udp_sockfd,newsockfd,qwe;
struct sockaddr_in tcp_servaddr,tcp_cliaddr,udp_servaddr;
char buff[1024];
//--------- TCP --------
tv.tv_sec=600;
tv.tv_usec=0;
if((tcp_sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
}
tcp_servaddr.sin_family= AF_INET;
tcp_servaddr.sin_port=htons(PORT);
tcp_servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(tcp_sockfd, (struct sockaddr *) &tcp_servaddr, sizeof(tcp_servaddr)) < 0)
{
perror("bind");
close(tcp_sockfd);
exit(1);
}
if(listen(tcp_sockfd, 2) < 0)
{
perror("listen");
close(tcp_sockfd);
exit(1);
}
clilen=sizeof(tcp_cliaddr);
FD_ZERO(&rfds);
FD_SET(tcp_sockfd,&rfds);
//-----------------------
//-------- UDP ----------
if((udp_sockfd=socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP))<0)
{
perror("socket");
}
udp_servaddr.sin_family= PF_INET;
udp_servaddr.sin_port=htons(PORT);
udp_servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(udp_sockfd, (struct sockaddr *) &udp_servaddr, sizeof(udp_servaddr)) < 0)
{
perror("bind");
close(udp_sockfd);
exit(1);
}
//----------------------
qwe=fork();
if(qwe==0){
printf("fork for TCP: PID %d\n",getpid());
while(1){
if(select(tcp_sockfd+1,&rfds,NULL,NULL,&tv)){
if(FD_ISSET(tcp_sockfd,&rfds)) {
newsockfd=accept(tcp_sockfd,(struct sockaddr*)&tcp_cliaddr,&clilen);
recv(newsockfd,buff,1024,0);
printf("\n%s\n",buff);
}
}
}
}
else{
while(1){
while(recvfrom(udp_sockfd, (void *)buff, 1024, 0, (struct sockaddr *)&udp_servaddr, &inputlength))
printf("\n%s\n",buff);
}
}
exit(EXIT_SUCCESS);
}