Socket tips: UDP Echo service - Client code
#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 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;
}
} int main(int argc, char * argv[])
{
char * server;
char * serverPort;
char * echoString;
size_t echoStringLength; struct addrinfo addrCriteria;
struct addrinfo *serverAddr;
int socketHandle;
int returnValue;
ssize_t receivedBytesCount;
ssize_t sendBytesCount;
struct sockaddr_storage responseAddr;
socklen_t responseAddrLen = sizeof(struct sockaddr);
char buffer[BUFFER_LENGTH + 1]; int broadcastPermission = 1; if(argc < 3 || argc > 4)
{
ExitWithMessage(1, "Parameters: <Server_IPv4> <Server_Port> <Message>");
} server = argv[1];
serverPort = argv[2];
echoString = argv[3];
echoStringLength = strlen(echoString); if(echoStringLength >= BUFFER_LENGTH)
{
ExitWithMessage(2, "Message is too long.");
} 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(server, serverPort, &addrCriteria, &serverAddr);
if(returnValue != 0)
{
fprintf(stderr, "getaddrinfo() failed.\n");
ExitWithMessage(returnValue, gai_strerror(returnValue));
} // Create a datagram/UDP socket
socketHandle = socket(serverAddr->ai_family, serverAddr->ai_socktype, serverAddr->ai_protocol);
if(socketHandle < 0)
{
fprintf(stderr, "socket() failed.\n");
ExitWithMessage(socketHandle, gai_strerror(socketHandle));
} // Set socket to be allowed broadcast returnValue = setsockopt(
socketHandle, SOL_SOCKET,
SO_BROADCAST,
(void *) &broadcastPermission,
sizeof(broadcastPermission)); if(returnValue != 0)
{
fprintf(stderr, "setsockopt() failed.\n");
ExitWithMessage(returnValue, gai_strerror(returnValue));
} sendBytesCount = sendto(socketHandle, echoString, echoStringLength, 0, serverAddr->ai_addr, serverAddr->ai_addrlen);
if(sendBytesCount < 0)
{
fprintf(stderr, "sendto() failed.\n");
ExitWithMessage(sendBytesCount, gai_strerror(sendBytesCount));
} // Receive a response receivedBytesCount = recvfrom(
socketHandle,
buffer,
BUFFER_LENGTH,
0,
(struct sockaddr *)&responseAddr,
&responseAddrLen); if(receivedBytesCount < 0)
{
fprintf(stderr, "recvfrom() failed.\n");
ExitWithMessage(receivedBytesCount, gai_strerror(receivedBytesCount));
} fputs("Server address: ", stdout);
PrintSocketAddress((struct sockaddr *)&responseAddr, stdout); buffer[receivedBytesCount] = '\0';
printf("\nResponse: %s\n", buffer); freeaddrinfo(serverAddr); return 0;
}
版权声明:本文博主原创文章,博客,未经同意不得转载。
Socket tips: UDP Echo service - Client code的更多相关文章
- Socket tips: UDP Echo service - Server code
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/soc ...
- Socket tips: 同意socket发送UDP Broadcast
假设创建一个UDP Socket: socketHandle = socket(serverAddr->ai_family, serverAddr->ai_socktype, server ...
- Linux 网络编程: echo Service
前言 大病初愈,感谢某人的陪伴,感谢王乐庆同学和赵攀同学的细心照顾.原以为过了第八周就不忙了,却没想到还有明天的党章考试.还是写代码比背党章有意思~趁着服务器还没过期,赶紧把 echo 完成了.关于错 ...
- 网络Socket编程UDP协议例子
服务端代码 public class UDPChatServer { //通讯端口 private Integer port=8000; //数据报文的通讯通道对象 private DatagramC ...
- socket和udp简介
socket简介 1.本地的进程间通信(IPC)有很多种方式,例如 队列 同步(互斥锁.条件变量等) 以上通信方式都是在一台机器上不同进程之间的通信方式,那么问题来了 网络中进程之间如何通信? 2. ...
- OData Client Code Generator
转发. [Tutorial & Sample] How to use OData Client Code Generator to generate client-side proxy cla ...
- OData – the best way to REST–实例讲解ASP.NET WebAPI OData (V4) Service & Client
一.概念介绍 1.1,什么是OData? 还是看OData官网的简单说明: An open protocol to allow the creation and consumption of quer ...
- 在socket的server端处理client端发来的数据
一.楔子 最近做了一个需求遇到一个坑,归结成一个小问题,其实就是在socket的server端处理client端发来的数据的问题,现将这个问题总结一下,本文将数据在server端以字典的形式存储. 另 ...
- [转]OData的初步认识 OData v4 Client Code Generator
本文转自:http://www.cnblogs.com/1zhk/p/5356053.html What – OData是什么? OData - Open Data Protocol,是一个设计和使用 ...
随机推荐
- 公司需求知识自学-Oracle的Package的作用及用法
Oracle的Package的作用 简化应用设计.提高应用性能.实现信息隐藏.子程序重载. 1.Oracle的Package除 了把存储过程放到一堆儿以外还有没有其他的作用(好处)? 你不觉得把存储过 ...
- 一个极其简洁的Python网页抓取程序,自己主动从雅虎財经抓取股票数据
本程序使用Python 2.7.6编写,扩展了Python自带的HTMLParser,自己主动依据预设的股票代码列表,从Yahoo Finance抓取列表中的数据日期.股票名称.实时报价.当日变化率. ...
- HTML 5最终确定,八年后,我们再谈谈如何改变世界
从原:http://www.36kr.com/p/216655.html 我们第一次谈论HTML5要改变世界大概是由于乔布斯,他坚持在iOS上不兼容Flash,在Adobe统治多媒体开发的那个年代.这 ...
- SignalR技术
Asp.net SignalR快速入门 一.前言 之前半年时间感觉自己有点浮躁,导致停顿了半年多的时间没有更新博客,今天重新开始记录博文,希望自己可以找回初心,继续沉淀.由于最近做的项目中用到Sign ...
- (23)unity4.6学习Ugui中国文档-------非官方Demo1
大家好,我是广东太阳. 转载请注明出处:http://write.blog.csdn.net/postedit/38922399 更全的内容请看我的游戏蛮牛地址:http://www.unitym ...
- slider使用TickPlacement获得游标效果
<Slider Name="slider游标效果" Maximum="3" SmallChange="0.25" TickPlacem ...
- Windows Phone开发(9):关于页面状态
原文:Windows Phone开发(9):关于页面状态 按照一般做法,刚学会如何导航,还是不够的,因为要知道,手机里面的每个页面,就如同Web页面一样,是无状态的. 啥是无状态?如果我们玩过Web开 ...
- UML用例图总结(转)
用例图主要用来描述“用户.需求.系统功能单元”之间的关系.它展示了一个外部用户能够观察到的系统功能模型图. [用途]:帮助开发团队以一种可视化的方式理解系统的功能需求. 用例图所包含的元素如下: 1. ...
- jquery 如何动态绑定传递到后台上传组件参数
$("#upload_photo").uploadify({ 'auto' : false, 'method' : "post", 'height' : 20, ...
- [文学阅读] METEOR: An Automatic Metric for MT Evaluation with Improved Correlation with Human Judgments
METEOR: An Automatic Metric for MT Evaluation with Improved Correlation with Human Judgments Satanje ...