udp.c

来自「STUN(RFC3489)客户端的简单实现」· C语言 代码 · 共 68 行

C
68
字号
#include <sys/types.h>#include <sys/socket.h>#include <net/if.h>#include <sys/ioctl.h>#include <arpa/inet.h>#include <netinet/in.h>#include <linux/sockios.h>#include <stdio.h>#include <errno.h>#include <stdlib.h>#include "udp.h"//open a UDP socket,return FILE DESCRIPTORint openSocket(void){	int fd;		if((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)	{		fprintf(stderr,"open socket failed:%s\n",strerror(errno));		exit(1);	}		return fd;                     }//close FILE DESCRIPTORvoid closeSocket(int fd){	close(fd);}/*fd for FILE DESCRIPTOR                 *//*return localhost's IP(local endian)    */unsigned int getLocalIP(int fd){	struct ifconf conf;	struct ifreq *ifr;	char buff[BUFSIZ];	int num;	int i;	int ip;	conf.ifc_len = BUFSIZ;	conf.ifc_buf = buff;	ioctl(fd, SIOCGIFCONF, &conf);	num = conf.ifc_len / sizeof(struct ifreq);	ifr = conf.ifc_req;	for(i=0; i<num; i++)	{		struct sockaddr_in *sin = (struct sockaddr_in *)(&ifr->ifr_addr);		ioctl(fd, SIOCGIFFLAGS, ifr);		if(((ifr->ifr_flags & IFF_LOOPBACK) == 0) && (ifr->ifr_flags & IFF_UP))		{			ip = ntohl(sin->sin_addr.s_addr);			break;		}		ifr++;	}	return ip;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?