c_cpp Linux的下UDP的Socket的编程示例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp Linux的下UDP的Socket的编程示例相关的知识,希望对你有一定的参考价值。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <dirent.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc , const char* argv[])
{
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in serv;
serv.sin_family = AF_INET;
serv.sin_port = htons(8888);
inet_pton(AF_INET, "127.0.0.1", &serv.sin_addr.s_addr);
char buf[256];
int ret;
while (1)
{
ret = read(STDIN_FILENO, buf, sizeof(buf));
if (ret > 0)
{
sendto(sockfd, buf, ret, 0, (struct sockaddr*)&serv, sizeof(serv));
ret = recvfrom(sockfd, buf, sizeof(buf), 0,(struct sockaddr*)NULL, NULL);
if (ret > 0)
{
write(STDOUT_FILENO, buf, ret);
}
}
}
close(sockfd);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <dirent.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ctype.h>
int main(int argc, const char* argv[])
{
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in serv;
serv.sin_family = AF_INET;
serv.sin_port = htons(8888);
serv.sin_addr.s_addr = INADDR_ANY;
bind(sockfd, (struct sockaddr*)&serv, sizeof(serv));
char buf[256];
int ret;
struct sockaddr_in client;
socklen_t clen = sizeof(client);
while (1)
{
ret = recvfrom(sockfd, buf, sizeof(buf),
0, (struct sockaddr*)&client, &clen);
if (ret > 0)
{
for (int i = 0;i<ret;i++)
{
buf[i] = toupper(buf[i]);
}
sendto(sockfd, buf, ret, 0, (struct sockaddr*)&client, clen);
}
}
close(sockfd);
return 0;
}
以上是关于c_cpp Linux的下UDP的Socket的编程示例的主要内容,如果未能解决你的问题,请参考以下文章
c_cpp Linux的下IPC通信之本地套接字
c_cpp Linux的下epoll的模型实现简单的HTTP服务器
c_cpp Linux Socket编程
linux下socket编程-UDP
Linux:UDP Socket编程(代码实战)
Linux:UDP Socket编程(代码实战)