Linux Socket编程实例(一个Hello World程序)

简介:

在Linux下写了个小的socket程序,分为客户端和服务器端,服务端开一个端口(2000),做为一个daemon,等待客户的连接请求.一旦有客户连接,服务器端打印出客户端的IP地址和端口,并且向服务器端发送欢迎信息和时间.下面是服务端的代码(tcpserver.c).由于这只是个简单的程序,所以只用了单线程实现!

ExpandedBlockStart.gif /* *
InBlock.gif * Tcp Server program, It is a simple example only.
InBlock.gif * zhengsh 200520602061 2
InBlock.gif * when client connect to server, send a welcome message and timestamp in server.
ExpandedBlockEnd.gif  
*/
 
None.gif
None.gif#include  <stdio.h> 
None.gif#include  <sys/socket.h> 
None.gif#include  <unistd.h> 
None.gif#include  <sys/types.h> 
None.gif#include  <netinet/ in.h> 
None.gif#include  <stdlib.h> 
None.gif#include  <time.h> 
None.gif 
None.gif #define  SERVER_PORT 20000   //   define the defualt connect port id 
None.gif #define  LENGTH_OF_LISTEN_QUEUE 10   //  length of listen queue in server 
None.gif #define  BUFFER_SIZE 255 
None.gif #define  WELCOME_MESSAGE "welcome to connect the server. " 
None.gif
None.gif int main( int argc,  char** argv)
ExpandedBlockStart.gif {
InBlock.gif       int  servfd,clifd;
InBlock.gif       struct  sockaddr_in servaddr,cliaddr;
InBlock.gif
InBlock.gif       if  ((servfd  =  socket(AF_INET,SOCK_STREAM, 0 ))  <   0 )
ExpandedSubBlockStart.gif         {
InBlock.gif              printf( " create socket error!\n " );
InBlock.gif              exit( 1 );
ExpandedSubBlockEnd.gif       }
 
InBlock.gif 
InBlock.gif       bzero( & servaddr, sizeof (servaddr));
InBlock.gif
InBlock.gif       servaddr.sin_family  =  AF_INET;
InBlock.gif       servaddr.sin_port  =  htons(SERVER_PORT);
InBlock.gif       servaddr.sin_addr.s_addr  =  htons(INADDR_ANY);
InBlock.gif
InBlock.gif       if  (bind(servfd,( struct  sockaddr * ) & servaddr, sizeof (servaddr)) < 0 )
ExpandedSubBlockStart.gif         {
InBlock.gif              printf( " bind to port %d failure!\n " ,SERVER_PORT);
InBlock.gif              exit( 1 );
ExpandedSubBlockEnd.gif       }
 
InBlock.gif 
InBlock.gif        if  (listen(servfd,LENGTH_OF_LISTEN_QUEUE)  <   0 )
ExpandedSubBlockStart.gif         {
InBlock.gif              printf( " call listen failure!\n " );
InBlock.gif              exit( 1 );
ExpandedSubBlockEnd.gif       }
 
InBlock.gif 
InBlock.gif        while  ( 1 )
ExpandedSubBlockStart.gif         // server loop will nerver exit unless any body kill the process 
InBlock.gif

InBlock.gif              char  buf[BUFFER_SIZE];
InBlock.gif              long  timestamp;
InBlock.gif              socklen_t length  =   sizeof (cliaddr);
InBlock.gif              clifd  =  accept(servfd,( struct  sockaddr * ) & cliaddr, & length);
InBlock.gif
InBlock.gif               if  (clifd  <   0 )
ExpandedSubBlockStart.gif                {
InBlock.gif                     printf( " error comes when call accept!\n " );
InBlock.gif                     break ;
ExpandedSubBlockEnd.gif              }
 
InBlock.gif 
InBlock.gif              strcpy(buf,WELCOME_MESSAGE);
InBlock.gif
InBlock.gif               // inet_ntop(INET_ADDRSTRLEN,cliaddr.sin_addr,buf,BUFFER_SIZE); 
InBlock.gif

InBlock.gif              printf( " from client,IP:%s,Port:%d\n " ,inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));
InBlock.gif
InBlock.gif              timestamp  =  time(NULL);
InBlock.gif
InBlock.gif              strcat(buf, " timestamp in server: " );
InBlock.gif              strcat(buf,ctime( & timestamp));
InBlock.gif
InBlock.gif              send(clifd,buf,BUFFER_SIZE, 0 );
InBlock.gif
InBlock.gif              close(clifd);           
InBlock.gif
ExpandedSubBlockEnd.gif       }
 // exit 
InBlock.gif
 
InBlock.gif       close(servfd);
InBlock.gif
InBlock.gif        return   0 ;
ExpandedBlockEnd.gif}


 客户每次用一个随机的端口连接服务器,并接收来自服务器的欢迎信息,然后打印出来(tcpclient).运行的时候接受一个参数,也就是服务器的ip地址.
ExpandedBlockStart.gif /*  Tcp client program, It is a simple example only.
InBlock.gif * zhengsh 200520602061 2
InBlock.gif * connect to server, and echo a message from server.
ExpandedBlockEnd.gif
*/
 
None.gif
None.gif
None.gif#include <stdio.h>
None.gif#include <sys/socket.h>
None.gif#include <unistd.h>
None.gif#include <sys/types.h>
None.gif#include <netinet/ in.h>
None.gif#include <stdlib.h> 
None.gif
None.gif
None.gif #define  SERVER_PORT 20000   //   define the defualt connect port id 
None.gif #define  CLIENT_PORT ((20001+rand())%65536)   //   define the defualt client port as a random port 
None.gif #define  BUFFER_SIZE 255 
None.gif #define  REUQEST_MESSAGE "welcome to connect the server.\n" 
None.gif
None.gif
None.gif void  usage( char* name)
ExpandedBlockStart.gif {
InBlock.gif       printf( " usage: %s IpAddr\n " ,name);
ExpandedBlockEnd.gif}

None.gif
None.gif
None.gif int  main( int argc,  char** argv)
ExpandedBlockStart.gif {
InBlock.gif       int  servfd,clifd,length = 0;
InBlock.gif       struct  sockaddr_in servaddr,cliaddr;
InBlock.gif       socklen_t socklen  =   sizeof (servaddr);
InBlock.gif       char  buf[BUFFER_SIZE];
InBlock.gif
InBlock.gif        if (argc < 2 )
ExpandedSubBlockStart.gif         {
InBlock.gif              usage(argv[ 0 ]);
InBlock.gif              exit( 1 );
ExpandedSubBlockEnd.gif       }
 
InBlock.gif
InBlock.gif       if ((clifd  =  socket(AF_INET,SOCK_STREAM, 0 ))  <   0 )
ExpandedSubBlockStart.gif         {
InBlock.gif             printf( " create socket error!\n " );
InBlock.gif             exit( 1 );
ExpandedSubBlockEnd.gif       }
 
InBlock.gif 
InBlock.gif       srand(time(NULL)); // initialize random generator 
InBlock.gif
 
InBlock.gif       bzero( & cliaddr, sizeof (cliaddr));
InBlock.gif       cliaddr.sin_family  =  AF_INET;
InBlock.gif       cliaddr.sin_port  =  htons(CLIENT_PORT);
InBlock.gif       cliaddr.sin_addr.s_addr  =  htons(INADDR_ANY);
InBlock.gif
InBlock.gif       bzero( & servaddr, sizeof (servaddr));
InBlock.gif       servaddr.sin_family  =  AF_INET;
InBlock.gif       inet_aton(argv[ 1 ], & servaddr.sin_addr);
InBlock.gif       servaddr.sin_port  =  htons(SERVER_PORT);
InBlock.gif      // servaddr.sin_addr.s_addr = htons(INADDR_ANY); 
InBlock.gif

InBlock.gif       if  (bind(clifd, (struct sockaddr* ) &cliaddr, sizeof (cliaddr)) < 0 )
ExpandedSubBlockStart.gif       {
InBlock.gif              printf( " bind to port %d failure!\n " ,CLIENT_PORT);
InBlock.gif              exit( 1 );
ExpandedSubBlockEnd.gif       }
 
InBlock.gif
InBlock.gif        if (connect(clifd,( struct  sockaddr * ) & servaddr, socklen)  <   0 )
ExpandedSubBlockStart.gif       {
InBlock.gif              printf( " can't connect to %s!\n ", argv[ 1 ]);
InBlock.gif              exit( 1 );
ExpandedSubBlockEnd.gif       }
 
InBlock.gif
InBlock.gif       length  =  recv(clifd, buf, BUFFER_SIZE, 0);
InBlock.gif        if  (length < 0)
ExpandedSubBlockStart.gif        {
InBlock.gif              printf( " error comes when recieve data from server %s! ", argv[1] );
InBlock.gif              exit( 1 );
ExpandedSubBlockEnd.gif       }
 
InBlock.gif
InBlock.gif       printf( " from server %s :\n\t%s", argv[1], buf);
InBlock.gif
InBlock.gif       close(clifd);
InBlock.gif       return 0;
ExpandedBlockEnd.gif}
 
None.gif



程序在Fedora core 4下通过编译,有几个warining.但是不影响.
目录
相关文章
|
1月前
|
安全 Linux Shell
Linux上执行内存中的脚本和程序
【9月更文挑战第3天】在 Linux 系统中,可以通过多种方式执行内存中的脚本和程序:一是使用 `eval` 命令直接执行内存中的脚本内容;二是利用管道将脚本内容传递给 `bash` 解释器执行;三是将编译好的程序复制到 `/dev/shm` 并执行。这些方法虽便捷,但也需谨慎操作以避免安全风险。
|
2月前
|
网络协议 Linux
Linux查看端口监听情况,以及Linux查看某个端口对应的进程号和程序
Linux查看端口监听情况,以及Linux查看某个端口对应的进程号和程序
145 2
|
2月前
|
Linux Python
linux上根据运行程序的进程号,查看程序所在的绝对路径。linux查看进程启动的时间
linux上根据运行程序的进程号,查看程序所在的绝对路径。linux查看进程启动的时间
47 2
|
9天前
|
消息中间件 分布式计算 Java
Linux环境下 java程序提交spark任务到Yarn报错
Linux环境下 java程序提交spark任务到Yarn报错
18 5
|
9天前
|
关系型数据库 MySQL 数据库
docker启动mysql多实例连接报错Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’
docker启动mysql多实例连接报错Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’
35 0
|
2月前
|
NoSQL Linux C语言
嵌入式GDB调试Linux C程序或交叉编译(开发板)
【8月更文挑战第24天】本文档介绍了如何在嵌入式环境下使用GDB调试Linux C程序及进行交叉编译。调试步骤包括:编译程序时加入`-g`选项以生成调试信息;启动GDB并加载程序;设置断点;运行程序至断点;单步执行代码;查看变量值;继续执行或退出GDB。对于交叉编译,需安装对应架构的交叉编译工具链,配置编译环境,使用工具链编译程序,并将程序传输到开发板进行调试。过程中可能遇到工具链不匹配等问题,需针对性解决。
|
2月前
|
Linux API
在Linux中,程序产生了库日志虽然删除了,但磁盘空间未更新是什么原因?
在Linux中,程序产生了库日志虽然删除了,但磁盘空间未更新是什么原因?
|
2月前
|
网络协议 Linux Shell
在Linux中,如何通过一个端口找到程序?
在Linux中,如何通过一个端口找到程序?
|
2月前
|
Linux Windows Python
最新 Windows\Linux 后台运行程序注解
本文介绍了在Windows和Linux系统后台运行程序的方法,包括Linux系统中使用nohup命令和ps命令查看进程,以及Windows系统中通过编写bat文件和使用PowerShell启动隐藏窗口的程序,确保即使退出命令行界面程序也继续在后台运行。
|
2月前
|
Linux Python
【Azure 应用服务】Azure App Service For Linux 上实现 Python Flask Web Socket 项目 Http/Https
【Azure 应用服务】Azure App Service For Linux 上实现 Python Flask Web Socket 项目 Http/Https
下一篇
无影云桌面