#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <time.h> #define BUFFER_LENGTH 1024 void ReverseMessage(char buffer[], ssize_t receivedBytesCount); void ExitWithMessage(const int errorCode, const char * errorMessage)
{
fprintf(stderr, "\n\nError Msg : %s\n", errorMessage);
fprintf(stderr, "Error Code : 0x%X\n", errorCode);
fprintf(stderr, "Location : %s: %d\n\n", __FILE__, __LINE__); exit(errorCode);
} void PrintIPv4(unsigned long ipvalue, FILE * stream)
{
uint8_t a;
uint8_t b;
uint8_t c;
uint8_t d; a = ipvalue >> 24; ipvalue -= a * 0x01000000;
b = ipvalue >> 16; ipvalue -= b * 0x00010000;
c = ipvalue >> 8; ipvalue -= c * 0100000100;
d = ipvalue; fprintf(stream, "%d.%d.%d.%d", d, c, b, a);
} void PrintSocketAddress(const struct sockaddr * address, FILE * stream)
{
struct in_addr ip4addr;
in_port_t port; struct sockaddr_in * ipv4Address; if(address == NULL || stream == NULL)
{
return;
} //printf("sa_family: %d\n", address->sa_family); switch(address->sa_family)
{
case AF_INET: fputs("[IPv4] ", stream); ipv4Address = (struct sockaddr_in *)address;
ip4addr = ipv4Address->sin_addr; port = ntohs(ipv4Address->sin_port); //fprintf(stream, "ip4addr.s_addr: %X\n", ip4addr.s_addr);
PrintIPv4(ip4addr.s_addr, stream);
fprintf(stream, " : %d", port); break;
case AF_INET6: fputs("[IPv6] ", stream); break;
default:
fputs("[unknown type]", stream);
return;
}
} void PrintTime(FILE * stream)
{
time_t currentTime;
struct tm * local_time;
struct timeval tv; currentTime = time(0);
local_time = localtime(¤tTime);
gettimeofday(&tv); fprintf(stream, "%04d-%02d-%02d %02d:%02d:%02d.%03d",
local_time->tm_year + 1900,
local_time->tm_mon + 1,
local_time->tm_mday,
local_time->tm_hour,
local_time->tm_min,
local_time->tm_sec,
tv.tv_usec / 1000); } int main(int argc, char * argv[])
{
char * serverPortString;
struct addrinfo addrCriteria;
struct addrinfo *serverAddr;
int socketHandle;
int returnValue; struct sockaddr_storage clientAddr;
socklen_t clientAddrLen = sizeof(struct sockaddr);
char buffer[BUFFER_LENGTH];
ssize_t receivedBytesCount;
ssize_t sendBytesCount; if(argc != 2)
{
//ExitWithMessage(0xF001, "Need parameter: <Server_Port>");
serverPortString = "2001";
}
else
{
// First argument: local port
serverPortString = argv[1];
} memset(&addrCriteria, 0, sizeof(struct addrinfo)); addrCriteria.ai_family = AF_UNSPEC; // Any address family
addrCriteria.ai_flags = AI_PASSIVE; // Accept on any address/port
addrCriteria.ai_socktype = SOCK_DGRAM; // only datagram socket
addrCriteria.ai_protocol = IPPROTO_UDP; // only UDP socket returnValue = getaddrinfo(NULL, serverPortString, &addrCriteria, &serverAddr);
if(returnValue != 0)
{
fprintf(stderr, "getaddrinfo() failed.\n");
ExitWithMessage(returnValue, gai_strerror(returnValue));
} // Create socket for incomming connections
socketHandle = socket(serverAddr->ai_family, serverAddr->ai_socktype, serverAddr->ai_protocol);
if(socketHandle < 0)
{
fprintf(stderr, "socket() failed.\n");
ExitWithMessage(socketHandle, gai_strerror(socketHandle));
} // Bind to local address
returnValue = bind(socketHandle, serverAddr->ai_addr, serverAddr->ai_addrlen);
if(returnValue < 0)
{
fprintf(stderr, "bind() failed.\n");
ExitWithMessage(returnValue, gai_strerror(returnValue));
} // Free address list allocated by getaddrinfo
freeaddrinfo(serverAddr); printf("Starting the UDP Server ...\n");
printf("Listinning at port %s\n\n", serverPortString); while(1)
{
receivedBytesCount = recvfrom(
socketHandle,
buffer,
BUFFER_LENGTH,
0,
(struct sockaddr *)&clientAddr,
&clientAddrLen); // printf("Received %d bytes.\n", receivedBytesCount); if(receivedBytesCount < 0)
{
fprintf(stderr, "recvfrom() failed.\n");
ExitWithMessage(receivedBytesCount, gai_strerror(receivedBytesCount));
} fputs("Handling client ", stdout);
PrintSocketAddress((struct sockaddr *)&clientAddr, stdout); fputs(" at ", stdout);
PrintTime(stdout); fputc('\n', stdout); buffer[receivedBytesCount] = '\0'; fputs("Message: ", stdout);
fputs(buffer, stdout);
fputs("\n\n", stdout); ReverseMessage(buffer, receivedBytesCount);
sendBytesCount = sendto(socketHandle, buffer, receivedBytesCount, 0, (struct sockaddr *)&clientAddr, sizeof(clientAddr));
if(sendBytesCount < 0)
{
fprintf(stderr, "sendto() failed.\n");
ExitWithMessage(sendBytesCount, gai_strerror(sendBytesCount));
}
} return 0;
} void ReverseMessage(char buffer[], ssize_t receivedBytesCount)
{
ssize_t i;
ssize_t j;
char temp; for(i = 0; i < receivedBytesCount / 2; i++)
{
j = receivedBytesCount - 1 - i; temp = buffer[i];
buffer[i] = buffer[j];
buffer[j] = temp;
}
}

Socket tips: UDP Echo service - Server code的更多相关文章

  1. Socket tips: UDP Echo service - Client code

    #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/soc ...

  2. Socket tips: 同意socket发送UDP Broadcast

    假设创建一个UDP Socket: socketHandle = socket(serverAddr->ai_family, serverAddr->ai_socktype, server ...

  3. 网络编程-UDP echo server

    1. UDP简介 UDP 和TCP 的区别包括 1. 面向字节流和面向报文 2. TCP必须要建立连接后才能进行数据交换,但是UDP则并没有连接的建立和释放过程.面向字节流说明,tcp报文段(segm ...

  4. Linux 网络编程: echo Service

    前言 大病初愈,感谢某人的陪伴,感谢王乐庆同学和赵攀同学的细心照顾.原以为过了第八周就不忙了,却没想到还有明天的党章考试.还是写代码比背党章有意思~趁着服务器还没过期,赶紧把 echo 完成了.关于错 ...

  5. 网络Socket编程UDP协议例子

    服务端代码 public class UDPChatServer { //通讯端口 private Integer port=8000; //数据报文的通讯通道对象 private DatagramC ...

  6. socket和udp简介

    socket简介 1.本地的进程间通信(IPC)有很多种方式,例如 队列 同步(互斥锁.条件变量等) 以上通信方式都是在一台机器上不同进程之间的通信方式,那么问题来了 网络中进程之间如何通信? 2. ...

  7. 【Socket编程】通过Socket实现UDP编程

    通过Socket实现UDP编程 UDP通信: 1.UDP协议(用户数据报协议)是无连接.不可靠.无序的. 2.UDP协议以数据报作为数据传输的载体. 3.使用UDP进行数据传输时,首先需要将要传输的数 ...

  8. 网络编程之socket(TCP,UDP)

    socket层 tcp协议和udp协议 1)Socket服务器编程 主要包括下面的几步: 1.打开socket 2.绑定到一个地址和端口 3.侦听进来的连接 4.接受连接 5.读写数据 (2)Sock ...

  9. python socket编程入门(编写server实例)+send 与sendall的区别与使用方法

    python 编写server的步骤: 1. 第一步是创建socket对象.调用socket构造函数.如: socket = socket.socket( family, type ) family参 ...

随机推荐

  1. EF中使用Contains方法

    第一种情况 var db=new ECEntities(); var list=new []{"8","9"}; var result=from a in db ...

  2. 关于EditText组件在android4.4W中出现黄色感叹号的问题?

    今天用eclipse编写android4.4W的项目,在XML中用到了EditText组件来写文本框,结果出现了黄色感叹号,还出现一句 This text field does not specify ...

  3. sql server 导出

    http://ssat.codeplex.com/SourceControl/latest 用于连接sql server

  4. android 样式开发

    1. Android的样式一般定义在res/values/styles.xml文件中,其中有一个根元素<resource>,而具体的每种样式定义则是通过<resource>下的 ...

  5. JavaScript 显示弹出窗口(二)

    window. open ( sURL , sName , sFeatures , bReplace ) sURL:可选项,被加载页面的html sName:可选项,指定打开的窗口的名字 _media ...

  6. 在Activity之间如何传递数据,请尽可能说出你所知道的传递数据的方法,并详细描述其实现过程。

    在Activity之间如何传递数据,请尽可能说出你所知道的传递数据的方法,并详细描述其实现过程. 答案:可以通过Intent对象.静态变量.剪切板和全局对象进行数据传递,具体的数据传递方法如下. 1. ...

  7. angular启动过程分析

    启动过程 步骤一 用自执行函数在代码完成加载后立即执行 function(window, document, undefined) 在window上暴露一个唯一的全局对象angular,Line250 ...

  8. Linux定时任务命令crontab

    作为一个php码农,linux接触总是很少,但又是必须会的一项技能,今天学到的linux命令是crontab命令. 注:以下总结基于Ubuntu 12.04 去/etc目录下看看 先去Ubuntu的/ ...

  9. php设计模式2策略模式

    <?php /** ****************************************************** * 策略模式:策略模式针对一组算法,将每一个算法封装到具有共同接 ...

  10. asp.net2.0app开发。

    asp.net app 网站开发:http://www.cnblogs.com/TerryFeng/archive/2009/05/15/1457731.html 在OPERA或M3GATE中设置编码 ...