Code Example:

The following programs demonstrate the use of getaddrinfo(), gai_strerror(), freeaddrinfo(), and  getnameinfo().  The programs are an echo server and client for UDP datagrams.

服务器端程序:
 ###Server program

        #include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h> #define BUF_SIZE 500 int
main(int argc, char *argv[])
{
struct addrinfo hints;
struct addrinfo *result, *rp;
int sfd, s;
struct sockaddr_storage peer_addr;
socklen_t peer_addr_len;
ssize_t nread;
char buf[BUF_SIZE]; if (argc != ) {
fprintf(stderr, "Usage: %s port\n", argv[]);
exit(EXIT_FAILURE);
} memset(&hints, , sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */
hints.ai_protocol = ; /* Any protocol */
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL; s = getaddrinfo(NULL, argv[], &hints, &result);
if (s != ) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
} /* getaddrinfo() returns a list of address structures.
Try each address until we successfully bind(2).
If socket(2) (or bind(2)) fails, we (close the socket
and) try the next address. */ for (rp = result; rp != NULL; rp = rp->ai_next) {
sfd = socket(rp->ai_family, rp->ai_socktype,
rp->ai_protocol);
if (sfd == -)
continue; if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == )
break; /* Success */ close(sfd);
} if (rp == NULL) { /* No address succeeded */
fprintf(stderr, "Could not bind\n");
exit(EXIT_FAILURE);
} freeaddrinfo(result); /* No longer needed */ /* Read datagrams and echo them back to sender */ for (;;) {
peer_addr_len = sizeof(struct sockaddr_storage);
nread = recvfrom(sfd, buf, BUF_SIZE, ,
(struct sockaddr *) &peer_addr, &peer_addr_len);
if (nread == -)
continue; /* Ignore failed request */ char host[NI_MAXHOST], service[NI_MAXSERV]; s = getnameinfo((struct sockaddr *) &peer_addr,
peer_addr_len, host, NI_MAXHOST,
service, NI_MAXSERV, NI_NUMERICSERV);
if (s == )
printf("Received %zd bytes from %s:%s\n",
nread, host, service);
else
fprintf(stderr, "getnameinfo: %s\n", gai_strerror(s)); if (sendto(sfd, buf, nread, ,
(struct sockaddr *) &peer_addr,
peer_addr_len) != nread)
fprintf(stderr, "Error sending response\n");
}
}

客户端程序:

  ###Client program

        #include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h> #define BUF_SIZE 500 int
main(int argc, char *argv[])
{
struct addrinfo hints;
struct addrinfo *result, *rp;
int sfd, s, j;
size_t len;
ssize_t nread;
char buf[BUF_SIZE]; if (argc < ) {
fprintf(stderr, "Usage: %s host port msg...\n", argv[]);
exit(EXIT_FAILURE);
} /* Obtain address(es) matching host/port */ memset(&hints, , sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
hints.ai_flags = ;
hints.ai_protocol = ; /* Any protocol */ s = getaddrinfo(argv[], argv[], &hints, &result);
if (s != ) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
} /* getaddrinfo() returns a list of address structures.
Try each address until we successfully connect(2).
If socket(2) (or connect(2)) fails, we (close the socket
and) try the next address. */ for (rp = result; rp != NULL; rp = rp->ai_next) {
sfd = socket(rp->ai_family, rp->ai_socktype,
rp->ai_protocol);
if (sfd == -)
continue; if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -)
break; /* Success */ close(sfd);
} if (rp == NULL) { /* No address succeeded */
fprintf(stderr, "Could not connect\n");
exit(EXIT_FAILURE);
} freeaddrinfo(result); /* No longer needed */ /* Send remaining command-line arguments as separate
datagrams, and read responses from server */ for (j = ; j < argc; j++) {
len = strlen(argv[j]) + ;
/* +1 for terminating null byte */ if (len + > BUF_SIZE) {
fprintf(stderr,
"Ignoring long message in argument %d\n", j);
continue;
} if (write(sfd, argv[j], len) != len) {
fprintf(stderr, "partial/failed write\n");
exit(EXIT_FAILURE);
} nread = read(sfd, buf, BUF_SIZE);
if (nread == -) {
perror("read");
exit(EXIT_FAILURE);
} printf("Received %zd bytes: %s\n", nread, buf);
} exit(EXIT_SUCCESS);
}

Come from url: http://man7.org/linux/man-pages/man3/getaddrinfo.3.html

UDP server Code的更多相关文章

  1. Socket tips: UDP Echo service - Server code

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

  2. TCP/UDP server

    Simple: Sample TCP/UDP server https://msdn.microsoft.com/en-us/library/aa231754(v=vs.60).aspx Simple ...

  3. epoll简介 与 UDP server的实现

    Abstractepoll是Linux内核为处理大批量句柄而作了改进的poll,是Linux下多路复用IO接口select/poll的增强版本,它能显著减少程序在大量并发连接中只有少量活跃的情况下的系 ...

  4. php创建udp Server

    <?php//服务器信息$server = 'udp://127.0.0.1:7002';//----UDP Server$msgEof = "\n";$socket = s ...

  5. UDP client,UDP server, TCP server, TCP client

    UDP server import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocke ...

  6. uip UDP server广播模式(client能够随意port,而且主动向client发送数据)

    眼下移植uip,发现UDP server模式下,必须指定本地port以及clientport,否则仅仅能讲clientport设置为0,才干接收随意port的数据,可是无法发送数据,由于此时clien ...

  7. 使用epoll实现一个udp server && client

    udp server #!/usr/bin/env python #-*- coding:utf-8 -*- import socket import select import Queue #创建s ...

  8. TCP/UDP Socket调试工具提供了TCP Server,TCP Client,UDP Server,UDP Client,UDP Group 五种Socket调试方案。

    一.TCP通信测试: 1)   创建TCP Server: 选中左方的TCP Server, 然后点击”创建”按钮,软件弹出监听端口输入框 输入监听端口后,即创建了一个在指定端口上进行监听的TCP S ...

  9. UDP Server

    //UDP服务器端程序,可以接受广播,不可接受多播,多播需要join播地址@Override public void run() { while (true) { try { DatagramSock ...

随机推荐

  1. shell逻辑运算符 1

    逻辑卷标 表示意思 1. 关于档案与目录的侦测逻辑卷标! -f 常用!侦测『档案』是否存在 eg: if [ -f filename ] -d 常用!侦测『目录』是否存在 -b 侦测是否为一个『 bl ...

  2. February 11 2017 Week 6 Saturday

    Love means never having to say you're sorry. 爱就是永远不必说对不起. Yesterday I heard an interesting story fro ...

  3. SAPGUI系统登录页面配置的SAProuter有什么用

    大家在安装完SAPGUI后,准备添加系统列表进行登录时,注意过这个SAProuter字段么? 从SAP的帮助文档上可以找到SAProuter的定义: https://help.sap.com/saph ...

  4. PTA练习题之7-1 出租车计价(15 分)

    7-1 出租车计价(15 分) 本题要求根据某城市普通出租车收费标准编写程序进行车费计算.具体标准如下: 起步里程为3公里,起步费10元: 超起步里程后10公里内,每公里2元: 超过10公里以上的部分 ...

  5. Ios国际化翻译工具

    IOS Translation Tool(IOS国际化翻译工具) 介绍 当IOS项目国际化的时候,手工去翻译每一个字符串是一件非常痛苦的事情.尤其是当项目中存在N多种语言.而且又很难保证,手工翻译的准 ...

  6. MongoDB创建集合、删除集合

    创建集合 createCollection() 方法 在 MongoDB 中,创建集合采用 db.createCollection(name, options) 方法. 语法格式 createColl ...

  7. PHP基础系列(二) PHP数组相关的函数分类整理

    之前写过一篇介绍 PHP字符串函数 的博文,这里写第二篇,本文主要介绍PHP 数组相关的函数: 一.检查数组中是否存在 array_key_exists — 检查给定的键名或索引是否存在于数组中 ar ...

  8. 备份&添加无线网络配置

    netsh wlan export profile key=clear folder=c:\ #备份 (ls c:\*.xml).FullName|%{netsh wlan add profile f ...

  9. python查看微信消息撤回

    准备环境 python语言环境 python解释器-pycharm itchat介绍 itchat是一个开源的微信个人号接口,通过itchat可以实现微信(好友或微信群)的信息处理,包括文本.图片.小 ...

  10. C# 面向对象之多态

    //多态:让一个对象表现的多种状态 //实现:子类重写父类的虚方法 Person person = new Person(); Chinese chinese = new Chinese(); Ame ...