Socket通信創建步驟:
(1)通過socket()函數創建socket
(2)通過bind函數綁定socket於設備地址
(3)進行讀寫操作read/recv/recvfrom write/send/sendto
(4)close方法關閉套接字
例子如下:
test1.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
intmain(void)
{
//createsocket
intfd=socket(AF_INET,SOCK_DGRAM,0);
if(fd==-1)
{
perror("socket ");
exit(-1);
}
printf("socketfd=%d ",fd);
//buildconnectionaddress
structsockaddr_inaddr;
addr.sin_family=AF_INET;
addr.sin_port=htons(6666);
addr.sin_addr.s_addr=inet_addr("127.0.0.1");
intr;
r=bind(fd,(structsockaddr*)&addr,sizeof(addr));
if(r==-1)
{
perror("bind");
close(fd);
exit(-1);
}
printf("bindaddresssuccessful! ");
//acceptorsendmessage
charbuf[255];
structsockaddr_infrom;
socklen_tlen;
len=sizeof(from);
塵梁空while(1)
{
r=recvfrom(fd,buf,sizeof(buf)-1,0,(structsockaddr*)&from,&len);
if(r>0)
{
buf[r]=0;
printf("Themessagefrom%sis:%s ",inet_ntoa(from.sin_addr),buf);
}
else
{
break;
}
}
//closesocket
close(fd);
return0;
}
test2.c
java">#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
intmain(void)
{
//createsocket
intfd=socket(AF_INET,SOCK_DGRAM,0);
if(fd==-1)
{
perror("socket");
exit(-1);
}
printf("createsocketOK! ");
//createansendaddress
structsockaddr_inaddr={};
addr.sin_family=AF_INET;
addr.sin_port=htons(6666);
addr.sin_addr.s_addr=inet_addr("127.0.0.1");
//
intr;
派瞎charbuf[255];
while(1)
{
r=read(0,buf,sizeof(buf)-1);
if(r<=0)
break;
sendto(fd,buf,r,0,(structsockaddr*)&addr,sizeof(addr));
}
//closesocket
渣凳close(fd);
return0;
}
先運行test1.c,然後運行test2.c,在test2.c運行後輸入內容,在test1.c所在終端中就會顯示信息
運行結果如下:
② 想問一個 關於linux下 socket編程的問題! 請進
1、 accept函數中,第三個參數原型是 socklen_t的,這是個什麼啊? 編譯的時候總是 說 它和int 的轉換無效! 應該怎麼修改?
a.accept的函數原型為int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);最後一個參數是socklen_t類型,沒記錯的話,他是unsigned int類型。所以譽做拍會有gcc會warning(g++則報錯,g++更嚴格)
2、編譯的時候 命令行輸入的是:
./TCPServer (伺服器IP) (埠號)
我想問的是,這個 伺服器IP和 埠號 在程序裡面是怎麼體現出來的?
是不是 那個 if(argc!=2) 決定的啊? 也就是命令行必須 輸出2個字元串。
如果輸出 三個字元串(包括埠號) 能行么? 哪位高手幫幫我啊!
a.伺服器的IP是寫死在慶羨程序里的,這句,
server_addr.sin_addr.s_addr=htonl(INADDR_ANY);INADDR_ANY表示讓協議棧自己選IP地址(針對多IP的情況);埠體現在這句 server_addr.sin_port=htons(portnumber);程序要求你輸入兩個字元串,其中第一個為程序名,第二個為埠號。比如你編譯出來的程序叫server,則命令為server 8888,就可以執行了。注意這里的argc等於幾表示連程序名稱在內總共有幾個字元串。
4、 最後的 close()函數 作用范圍不明!
因為你調用了socket函數打開了一個描述字sockfd,所以這里要把他關閉。
newfd是你accept返回的描述字,前面已經關了,這兩個是不一樣的。sockfd用來監聽,newfd用來與建立連接的對端通訊。
另外,你露了頭文件,所以warning
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <胡老netinet/in.h>
#include <sys/socket.h>
#define WAITBUF 10
#include <unistd.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int sockfd,new_fd;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
socklen_t sin_size;
int portnumber;
char hello[]="Hello! Socket communication world!\n";
if(argc!=2)
{
fprintf(stderr,"Usage:%s portnumber\a\n",argv[0]);
exit(1);
}
/*埠號不對,退出*/
if((portnumber=atoi(argv[1]))<0)
{
fprintf(stderr,"Usage:%s portnumber\a\n",argv[0]);
exit(1);
}
/*伺服器端開始建立socket描述符*/
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
fprintf(stderr,"Socket error:%s\n\a",strerror(errno));
exit(1);
}
/*伺服器端填充 sockaddr結構*/
bzero(&server_addr,sizeof(struct sockaddr_in));
server_addr.sin_family=AF_INET;
/*自動填充主機IP*/
server_addr.sin_addr.s_addr=htonl(INADDR_ANY);
server_addr.sin_port=htons(portnumber);
/*捆綁sockfd描述符*/
if(bind(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))==-1)
{
fprintf(stderr,"Bind error:%s\n\a",strerror(errno));
exit(1);
}
/*監聽sockfd描述符*/
if(listen(sockfd, WAITBUF)==-1)
{
fprintf(stderr,"Listen error:%s\n\a",strerror(errno));
exit(1);
}
while(1)
{
/*伺服器阻塞,直到客戶程序建立連接*/
sin_size=sizeof(struct sockaddr_in);
if((new_fd=accept(sockfd,(struct sockaddr *)(&client_addr),&sin_size))==-1)
{
fprintf(stderr,"Accept error:%s\n\a",strerror(errno));
exit(1);
}
/*可以在這里加上自己的處理函數*/
fprintf(stderr,"Server get connection from %s\n",
inet_ntoa(client_addr.sin_addr));
if(send(new_fd,hello,strlen(hello),0)==-1)
{
fprintf(stderr,"Write Error:%s\n",strerror(errno));
exit(1);
}
/*這個通信已經結束*/
close(new_fd);
/*循環下一個*/
}
close(sockfd);
exit(0);
}
③ linux下socket編程初級問題,求助,急
你設斷點查吧,我一下也看不出來
④ linux下C語言socket編程雙機互發數據
這個問題很好辦啦,伺服器接受一個連接請求,然後開一個線程或者進程都可以,再在線程或者進程裡面採用其他技術實現同時收發(比如I/O復用,比如非阻塞I/O)。客戶端也可以採用I/O復用。
推薦資料的話,《unix網路編程》這本書很好,公認的經典,當教科書用,這本書里有你想要的所有內容。
ps:你基礎太差,多補補吧,別想一下吃個胖子。
另外我這里正好有個例子滿足你的要求,貼給你,自己寫的,不是網上找的,用的是多進程加I/O復用技術:
server端:
/****************************************************************
**
**
**
****************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>
#define BUFLEN 1024
#define MAX(a,b) ((a)>(b)?(a):(b))
typedef void Sigfunc (int);
void str_echo(FILE *,int);
//Sigfunc *signal(int, Sigfunc *);
int main(int argc,char **argv)
{
int connfd,listenfd;
pid_t childpid;
socklen_t clilen;
struct sockaddr_in cliaddr,servaddr;
void sig_chld(int);
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(5358);
bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
listen(listenfd,8);
signal(SIGCHLD,sig_chld);
while(1)
{
clilen = sizeof(cliaddr);
if((connfd = accept(listenfd,(struct sockaddr*)&cliaddr,&clilen)) < 0)
{
if(errno == EINTR)
{
fputs("accept error: EINTR\n",stdout);
continue;
}
else
{
fputs("accept error..\n",stdout);
}
}
if((childpid = fork()) == 0)
{
close(listenfd);
str_echo(stdin,connfd);
exit(0);
}
close(connfd);
}
}
void str_echo(FILE *fp,int sockfd)
{
int n = 0;
char sendbuf[BUFLEN] = { 0 },recvbuf[BUFLEN] = { 0 };
int maxfdp;
fd_set rset;
FD_ZERO(&rset);
while(1)
{
FD_SET(fileno(fp),&rset);
FD_SET(sockfd, &rset);
maxfdp = MAX(fileno(fp),sockfd)+1;
select(maxfdp, &rset ,NULL, NULL, NULL);
if(FD_ISSET(sockfd, &rset))
{
if(n = read(sockfd, recvbuf, BUFLEN) == 0)
{
return;
}
if(n == -1)
{
break;
}
printf("%s\n",recvbuf);
memset(recvbuf,0,BUFLEN);
}
if(FD_ISSET(fileno(fp),&rset))
{
scanf("%s",sendbuf);
write(sockfd, sendbuf,strlen(sendbuf));
}
}
}
void sig_chld (int signo)
{
pid_t pid;
int stat;
while ((pid = waitpid(-1,&stat, WNOHANG)) > 0)
{
printf("child %d terminated\n",pid);
}
return;
}
client端:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#define MAX(a,b) (a)>(b)?(a):(b)
int main()
{
int s,connectReturn, maxfd;
fd_set rset;
char sendbuf[1024] = {0};
char recvbuf[1024] = {0};
long port=5358;
s=socket(PF_INET,SOCK_STREAM,0);
struct sockaddr_in sa;
sa.sin_family=AF_INET;
sa.sin_addr.s_addr=inet_addr("127.0.0.1");
sa.sin_port=htons(port);
connectReturn=connect(s,(struct sockaddr *)&sa,sizeof(sa));
printf("%d\n",connectReturn);
FD_ZERO(&rset);
while(1)
{
FD_SET(fileno(stdin), &rset);
FD_SET(s, &rset);
maxfd=MAX(fileno(stdin), s) + 1;
select(maxfd, &rset, NULL, NULL, NULL);
if(FD_ISSET(fileno(stdin), &rset))
{
scanf("%s",sendbuf);
send(s,sendbuf,strlen(sendbuf),0);
bzero(sendbuf, 1024);
}
else if(FD_ISSET(s, &rset))
{
memset(recvbuf,0,1024);
recv(s,recvbuf,1024,0);
printf("remote: %s\n",recvbuf);
}
}
return 0;
}
⑤ linux下的 socket編程問題!
第一個問題:
對,是那樣的,用open打開文件,用read讀取文件,在發送給對方,接收方接收到後,寫入文件就可以了。不過在這個過程中最好別用字元串函數,除非你很熟悉。
第二個問題
首先你得去搞清楚什麼是線程,什麼是進程,fork出來的叫進程,pthread_create出來的才叫線程。伺服器有很多種模型(多進程,多線程,select,epoll模型,這個我的blog上有,famdestiny.cublog.cn),不一定要用多進程。
給你寫了個代碼,自己先看看:
注意,在自己的目錄下創建一個叫pserverb的文件,程序會把這個文件復製成test文件。你可以自己根據需要改改
server:
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define SERV_PORT 5358
#define MAX_CONN 10
#define BUF_LEN 1024
void str_echo(FILE *fp, int sockfd){
ssize_t nread;
int file_fd;
char buf[BUF_LEN] = {0};
file_fd = open("test", O_WRONLY | O_TRUNC | O_CREAT, 0755);
while(1) {
bzero(buf, BUF_LEN);
if((nread = read(sockfd, buf, BUF_LEN)) == -1) {
if(errno == EINTR) {
continue;
}
else {
printf("readn error: %s\n", strerror(errno));
continue;
}
}
else if (nread == 0) {
break;
}
else {
printf("%s\n", buf);
write(file_fd, buf, nread);
}
}
close(file_fd);
}
void sig_chld(int sig){
pid_t pid;
int state;
while((pid = waitpid(-1, &state, WNOHANG)) > 0){
printf("child process %d exited.", pid);
}
return;
}
int main(int argc, char **argv)
{
int listenfd, connfd;
socklen_t cliaddrlen;
pid_t childpid;
struct sockaddr_in servaddr, cliaddr;
if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
printf("socket error: %s\n", strerror(errno));
return 0;
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
if(bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1){
printf("bind error: %s\n", strerror(errno));
return 0;
}
if(listen(listenfd, MAX_CONN) == -1){
printf("listen error: %s\n", strerror(errno));
return 0;
}
signal(SIGCHLD, sig_chld);
while(1){
cliaddrlen = sizeof(cliaddr);
if((connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddrlen)) == -1){
if(errno == EINTR){
continue;
}
else{
printf("accept error: %s\n", strerror(errno));
continue;
}
}
if((childpid = fork()) == 0){
close(listenfd);
str_echo(stdin, connfd);
exit(0);
}
else if(childpid > 0){
close(connfd);
}
else{
printf("fork error!\n");
continue;
}
}
}
client:
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#define SERV_ADDR "127.0.0.1"
#define SERV_PORT 5358
#define BUF_LEN 1024
void str_cli(char *path, int sockfd)
{
char sendbuf[BUF_LEN] = {0};
int fd, n;
if((fd = open("./pserverb", O_RDONLY)) == -1){
printf("%s\n", strerror(errno));
exit(0);
}
while((n = read(fd, sendbuf, BUF_LEN)) != 0) {
if(n < 0){
printf("%s\n", strerror(errno));
exit(0);
}
write(sockfd, sendbuf, n);
bzero(sendbuf, BUF_LEN);
}
close(fd);
return;
}
int main(int argc, char **argv)
{
int fd;
struct sockaddr_in servaddr;
fd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(SERV_ADDR);
servaddr.sin_port = htons(SERV_PORT);
if (connect(fd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1) {
printf("connect error: %s\n", strerror(errno));
return 0;
}
str_cli(argv[1], fd);
return 0;
}
⑥ Linux socket編程問題求教,client和server為什麼時能連接,時不能連接求指導謝謝
你的程序就是時能連接,時不連接,英文你寫完後就close掉了,所以就是那個現象!!!
⑦ Linux Socket編程求助啊,一個伺服器和多個客戶端通信問題求助
如果客戶端並發連接數不是很大,比如50個以下,可以用如下模型:
建立一個監聽主線程,循環監聽埠。
當有客戶端連接鍵碰時,建立客戶端通訊線程,並保留客戶端源穗socket到鏈表中。稿裂談
當客戶端斷開連接時,從socket鏈表中刪除該socket。
⑧ linux下原始套接字(SOCK_RAW)綁定網卡
好像沒有辦法綁定網卡
buff裡麵包含櫻皮源鏈路層的數脊態據,mac層頭+IP頭+TCP或UDP頭
如果想過濾握州,可以直接寫代碼完成
⑨ linux下socket 網路編程(客戶端向伺服器端發送文件) 求源代碼 大哥大姐幫幫忙 。。謝謝
server:
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <syslog.h>
#include <sys/time.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#define MAXDATASIZE 1024
#define SERVPORT 19999
#define BACKLOG 10
int SendFileToServ(const char *path, const char *FileName, const char *ip)
{
#define PORT 20002
int sockfd;
int recvbytes;
char buf[MAXDATASIZE];
char send_str[MAXDATASIZE];
char filepath[128] = {0};
struct sockaddr_in serv_addr;
FILE *fp;
sprintf(filepath, "%s%s", path, FileName);
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket");
return 1;
}
bzero(&serv_addr,sizeof(struct sockaddr_in));
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(PORT);
inet_aton(ip, &serv_addr.sin_addr);
int IErrCount = 0;
again:
if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr))==-1)
{
if (5 == IErrCount)
return 1;
IErrCount++;
perror("connect");
sleep(2);
goto again;
}
//if ((fp = fopen(FileName, "rb")) == NULL)
if ((fp = fopen(filepath, "rb")) == NULL)
{
perror("fopen ");
return 1;
}
recvbytes = write(sockfd, FileName, strlen(FileName));
recvbytes = read(sockfd, buf, MAXDATASIZE);
if (!memcmp(buf, "sendmsg", 7))
{
while(fgets(send_str, MAXDATASIZE, fp))
{
recvbytes = write(sockfd, send_str, strlen(send_str));
recvbytes = read(sockfd, buf, MAXDATASIZE);
if (recvbytes <= 0)
{
fclose(fp);
close(sockfd);
return 1;
}
if (memcmp(buf, "goon", 4))
{
fclose(fp);
close(sockfd);
return 1;
}
}
recvbytes = write(sockfd, "end", 3);
}
else
{
fclose(fp);
close(sockfd);
return 1;
}
memset(buf, 0, MAXDATASIZE);
if (read(sockfd, buf, MAXDATASIZE) <= 0)
{
close(sockfd);
return 2;
}
char *Eptr = "nginx reload error";
//printf("bf[%s]\n", buf);
int ret;
ret = strncmp(buf, Eptr, strlen(Eptr));
//printf("%d\n", ret);
if (!ret)
{
close(sockfd);
return 2;
}
close(sockfd);
return 0;
}
int mysyslog(const char * msg)
{
FILE *fp;
if ((fp = fopen("/tmp/tmp.log", "a+")) == NULL)
{
return 0;
}
fprintf(fp, "[%s]\n", msg);
fclose(fp);
return 0;
}
static void quit_handler(int signal)
{
kill(0, SIGUSR2);
syslog( LOG_NOTICE, "apuserv quit...");
// do something exit thing ,such as close socket ,close mysql,free list
// .....
//i end
exit(0);
}
static int re_conf = 0;
static void reconf_handler(int signal)
{
re_conf=1;
syslog(LOG_NOTICE,"apuserv reload configure file .");
// 請在循環體中判斷,如果re_conf == 1,請再次載入配置文件。
}
static int isrunning(void)
{
int fd;
int ret;
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = 0;
lock.l_start = 0;
lock.l_len = 0;
const char *lckfile = "/tmp/apuserv.lock";
fd = open(lckfile,O_WRONLY|O_CREAT);
if (fd < 0) {
syslog(LOG_ERR,"can not create lock file: %s\n",lckfile);
return 1;
}
if ((ret = fcntl(fd,F_SETLK,&lock)) < 0) {
ret = fcntl(fd,F_GETLK,&lock);
if (lock.l_type != F_UNLCK) {
close(fd);
return lock.l_pid;
}
else {
fcntl(fd,F_SETLK,&lock);
}
}
return 0;
}
int MyHandleBuff(const char *buf, char *str, char *FileName, char *pth)
{
sscanf(buf, "%s %s %s", pth, FileName, str);
printf("path=%s\nfilename=%s\nip=%s\n", pth, FileName, str);
return 0;
}
int main(int argc, char **argv)
{
int sockfd,client_fd;
socklen_t sin_size;
struct sockaddr_in my_addr,remote_addr;
char buff[MAXDATASIZE];
int recvbytes;
#if 1
int pid ;
char ch ;
int ret;
int debug = 0;
signal(SIGUSR1, SIG_IGN);
signal(SIGUSR2, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGTERM, quit_handler);
syslog(LOG_NOTICE,"apuserver start....");
while ((ch = getopt(argc, argv, "dhV")) != -1) {
switch (ch) {
case 'd':
debug = 1;
break;
case 'V':
printf("Version:%s\n","1.0.0");
return 0;
case 'h':
printf(" -d use daemon mode\n");
printf(" -V show version\n");
return 0;
default:
printf(" -d use daemon mode\n");
printf(" -V show version\n");
}
}
if (debug && daemon(0,0 ) ) {
return -1;
}
if (isrunning()) {
fprintf(stderr, "apuserv is already running\n");
syslog(LOG_INFO,"apuserv is already running\n");
exit(0);
}
while (1) {
pid = fork();
if (pid < 0)
return -1;
if (pid == 0)
break;
while ((ret = waitpid(pid, NULL, 0)) != pid) {
syslog(LOG_NOTICE, "waitpid want %d, but got %d", pid, ret);
if (ret < 0)
syslog(LOG_NOTICE, "waitpid errno:%d", errno);
}
kill(0, SIGUSR2);
sleep(1);
syslog(LOG_NOTICE,"restart apuserver");
}
signal(SIGHUP, reconf_handler);
signal(SIGPIPE, SIG_IGN);
signal(SIGUSR1,SIG_IGN);
signal(SIGUSR2, SIG_DFL);
signal(SIGTERM, SIG_DFL);
#endif
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket");
exit(1);
}
bzero(&my_addr,sizeof(struct sockaddr_in));
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1)
{
perror("bind");
exit(1);
}
if(listen(sockfd,BACKLOG)==-1)
{
perror("listen");
exit(1);
}
int nret;
while(1)
{
sin_size = sizeof(struct sockaddr_in);
if((client_fd = accept(sockfd, (struct sockaddr *)&remote_addr, &sin_size))==-1)
{
perror("falied accept");
continue;
}
memset(buff, 0, MAXDATASIZE);
recvbytes = read(client_fd, buff, MAXDATASIZE);
char str[16] = {0};
char FileName[128] = {0};
char path[128] = {0};
MyHandleBuff(buff, str, FileName, path);
if (recvbytes > 0)
{
nret = SendFileToServ(path, FileName, str);
printf("nret[%d]\n", nret);
if (1 == nret)
write(client_fd, "send file error", 15);
else if(2 == nret)
write(client_fd, "reload nginx error", 18);
else
write(client_fd, "succ", 4);
}
close(client_fd);
}
}
_________________________________________________
client:
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <syslog.h>
#include <sys/time.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#define MAXDATASIZE 1024
#define SERVPORT 20002
#define BACKLOG 10
int mysyslog(const char * msg)
{
FILE *fp;
if ((fp = fopen("/tmp/tmp.log", "a+")) == NULL)
{
return 0;
}
fprintf(fp, "[%s]\n", msg);
fclose(fp);
return 0;
}
static void quit_handler(int signal)
{
kill(0, SIGUSR2);
syslog( LOG_NOTICE, "apuserv quit...");
// do something exit thing ,such as close socket ,close mysql,free list
// .....
//i end
exit(0);
}
static int re_conf = 0;
static void reconf_handler(int signal)
{
re_conf=1;
syslog(LOG_NOTICE,"apuserv reload configure file .");
// ????·???????1nf == 1£???′μ?????
static int isrunning(void)
{
int fd;
int ret;
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = 0;
lock.l_start = 0;
lock.l_len = 0;
const char *lckfile = "/tmp/dstserver.lock";
fd = open(lckfile,O_WRONLY|O_CREAT);
if (fd < 0) {
syslog(LOG_ERR,"can not create lock file: %s\n",lckfile);
return 1;
}
if ((ret = fcntl(fd,F_SETLK,&lock)) < 0) {
ret = fcntl(fd,F_GETLK,&lock);
if (lock.l_type != F_UNLCK) {
close(fd);
return lock.l_pid;
}
else {
fcntl(fd,F_SETLK,&lock);
}
}
return 0;
}
int main(int argc, char **argv)
{
int sockfd,client_fd;
socklen_t sin_size;
struct sockaddr_in my_addr,remote_addr;
char buff[MAXDATASIZE];
int recvbytes;
#if 1
int pid ;
char ch ;
int ret;
int debug = 0;
signal(SIGUSR1, SIG_IGN);
signal(SIGUSR2, SIG_IGN);
signal(SIGHUP, SIG_IGN);
signal(SIGTERM, quit_handler);
syslog(LOG_NOTICE,"dstserver start....");
while ((ch = getopt(argc, argv, "dhV")) != -1) {
switch (ch) {
case 'd':
debug = 1;
break;
case 'V':
printf("Version:%s\n","1.0.0");
return 0;
case 'h':
printf(" -d use daemon mode\n");
printf(" -V show version\n");
return 0;
default:
printf(" -d use daemon mode\n");
printf(" -V show version\n");
}
}
if (debug && daemon(0,0 ) ) {
return -1;
}
if (isrunning()) {
fprintf(stderr, "dstserver is already running\n");
syslog(LOG_INFO,"dstserver is already running\n");
exit(0);
}
while (1) {
pid = fork();
if (pid < 0)
return -1;
if (pid == 0)
break;
while ((ret = waitpid(pid, NULL, 0)) != pid) {
syslog(LOG_NOTICE, "waitpid want %d, but got %d", pid, ret);
if (ret < 0)
syslog(LOG_NOTICE, "waitpid errno:%d", errno);
}
kill(0, SIGUSR2);
sleep(1);
syslog(LOG_NOTICE,"restart apuserver");
}
signal(SIGHUP, reconf_handler);
signal(SIGPIPE, SIG_IGN);
signal(SIGUSR1,SIG_IGN);
signal(SIGUSR2, SIG_DFL);
signal(SIGTERM, SIG_DFL);
#endif
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("socket");
exit(1);
}
bzero(&my_addr,sizeof(struct sockaddr_in));
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1)
{
perror("bind");
exit(1);
}
if(listen(sockfd,BACKLOG)==-1)
{
perror("listen");
exit(1);
}
char filepath[MAXDATASIZE]= {0};
FILE *fp;
while(1)
{
sin_size = sizeof(struct sockaddr_in);
if((client_fd = accept(sockfd, (struct sockaddr *)&remote_addr, &sin_size))==-1)
{
perror("falied accept");
continue;
}
memset(buff, 0, MAXDATASIZE);
recvbytes = read(client_fd, buff, MAXDATASIZE);
sprintf(filepath, "/etc/nginx/url_rule/%s", buff);
if ((fp = fopen(filepath, "wb")) == NULL)
{
perror("fopen");
close(client_fd);
continue;
}
write(client_fd, "sendmsg", 7);
while(read(client_fd, buff, MAXDATASIZE))
{
if (!memcmp(buff, "end", 3))
{
fclose(fp);
break;
}
else
{
fprintf(fp, "%s", buff);
write(client_fd, "goon", 4);
}
}
//system("nginx -s reload");
char *Sptr = "nginx reload succ";
char *Eptr = "nginx reload error";
int ret;
ret = system("nginx -s reload");
printf("ret[%d]\n", ret);
if (ret != 0)
{
write(client_fd, Eptr, strlen(Eptr));
}
else
{
write(client_fd, Sptr, strlen(Sptr));
}
close(client_fd);
}
}
以前寫的:內容忘記了。不是很復雜你可以自己看!
⑩ linux socket編程、server端有幾個socket綁定不同埠、想用select函數實
fd_set rdfds; /* 先申明一個 fd_set 集合來保存我們要檢測的 socket句柄 */
struct timeval tv; /* 申明一個時間變數來保存時間 */
int ret; /* 保存返回值 */
FD_ZERO(&rdfds); /* 用select函數之前先把集合清零 */
FD_SET(socket, &rdfds); /* 把要檢測的句柄socket加入到集合里 */
tv.tv_sec = 1;
tv.tv_usec = 500; /* 設置select等待的最大時間為1秒加500毫秒 */
ret = select(socket + 1, &rdfds, NULL, NULL, &tv); /* 檢測我們上面設置到集合rdfds里的句柄是否有可讀信息 */
if(ret < 0) perror("select");/* 這說明select函數出錯 */
else if(ret == 0) printf("超時\n"); /* 說明在我們設定的時間值1秒加500毫秒的時間內,socket的狀態沒有發生變化 */
else { /* 說明等待時間還未到1秒加500毫秒,socket的狀態發生了變化 */
printf("ret=%d\n", ret); /* ret這個返回值記錄了發生狀態變化的句柄的數目,由於我們只監視了socket這一個句柄,所以這里一定正大ret=1,如果同時有多個句柄舉陵豎發生變化返回的就是句柄的總和了 */
/* 這里我們就應該從socket這個句柄里讀取數據了,因為select函數已經告訴我們這個句柄里有數據可讀 */
if(FD_ISSET(socket, &rdfds)) { /* 先判斷一下socket這外被監視的句柄是否真的變成可讀的了 */
/* 讀取socket句汪賀柄里的數據 */
recv(...);
}
}