UDP服务器
service.c
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[]){
if(argc != 3){
printf("Usage: %s [ip] [port]\n", argv[0]);
return 1;
}
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if(sock < 0){
perror("socket");
return 2;
}
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_port = htons(atoi(argv[2]));
local.sin_addr.s_addr = inet_addr(argv[1]);
if(bind(sock, (struct sockaddr*)&local,sizeof(local)) < 0){
perror("bind");
return 3;
}
char buf[1024];
struct sockaddr_in client;
while(1){
socklen_t len = sizeof(client);
ssize_t s = recvfrom(sock, buf, sizeof(buf) - 1, 0, (struct sockaddr*)&client, &len);
if(s > 0){
buf[s] = 0;
printf("[%s][%d]: %s\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port), buf);
sendto(sock, buf, strlen(buf), 0, (struct sockaddr*)&client, sizeof(client));
}
}
close(sock);
return 0;
}
client.c
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[2]){
if(argc != 3){
printf("Usage:%s [ip] [port]",argv[0]);
return 1;
}
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if(sock < 0){
perror("socket");
return 2;
}
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[2]));
server.sin_addr.s_addr = inet_addr(argv[1]);
char buf[1024];
struct sockaddr_in peer;
while(1){
socklen_t len = sizeof(peer);
printf("please Enter# ");
fflush(stdout);
ssize_t s = read(0, buf, sizeof(buf) - 1);
if(s > 0){
buf[s - 1] = 0;
sendto(sock, buf, strlen(buf), 0, (struct sockaddr*)&server, sizeof(server));
ssize_t _s = recvfrom(sock, buf, sizeof(buf) - 1, 0, (struct sockaddr*)&peer, &len);
if(_s > 0){
buf[_s] = 0;
printf("server echo# %s\n", buf);
}
}
}
close(sock);
return 0;
}
一般不绑定,编口必须为众所周知的,且不能任意修改。1024以后
lo: flags=73 mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
127.0.0.1本地测试(回寄地址)
Makefile:
.PHONY:all
all:service client
service:service.c
gcc -o $@ $^
client:client.c
gcc -o $@ $^ -static
.PHONY:clean
clean:
rm -r service client
切换到root用户:yum install glibc-static
加载:fastestmirror,langpacks 插件
远程拷贝:scp client 192.168.3.179:/home
当前linux服务器直接通过ssh连接到另外一台linux服务器:另外一台服务器IP位192.168.1.1,用户名为zzz,密码为123
则:ssh [email protected] 然后输入密码:123 则可以登陆成功,exit命令退出ssh登录。
在多线程环境下,推荐使用inet_ntop,这个函数由调用者提供一个缓冲区保存结果,可以规避线程安全问题。