- 论坛徽章:
- 0
|
本帖最后由 firecityplans 于 2011-10-08 23:31 编辑
今天小写了一个程序,感觉不是太安全,但是又找不到在哪儿,在这里请大家来讨论。谢谢了!
此socket程序主要是使用apache apr可移植库来编写的,但和C语言相关性很大。
socket server:
- #define BUFLEN 30
- #define PORT 5671
- int main()
- {
- apr_status_t rv;
- apr_pool_t *mp;
- apr_socket_t *sock1 = NULL;
- apr_socket_t *from = NULL;
- char sndbuf[BUFLEN] = "abcdefghigklmn";
- char *rcvbuf;
- apr_sockaddr_t *sa;
- apr_size_t len =30;
- apr_size_t *plen = &len;
- apr_initialize();
- apr_pool_create(&mp,NULL);
- rcvbuf = apr_palloc(mp,BUFLEN);
- if ( (rv = apr_sockaddr_info_get(&sa,APR_UNSPEC,APR_INET,PORT,0,mp)) != APR_SUCCESS )
- {
- fprintf(stderr,"get sockaddr info fail: %s \n",strerror(errno));
- exit(1);
- }
- if( (rv = apr_socket_create(&sock1,sa->family,SOCK_STREAM,APR_PROTO_TCP,mp) ) != APR_SUCCESS )
- {
- fprintf(stderr,"create socket fail: %s \n",strerror(errno));
- exit(1);
- }
- if( (rv = apr_socket_bind(sock1,sa) ) !=APR_SUCCESS )
- {
- fprintf(stderr,"bind socket fail :%s \n",strerror(errno));
- exit(1);
- }
- if( (rv = apr_socket_listen(sock1,10)) !=APR_SUCCESS )
- {
- fprintf(stderr,"listen socket fail: %s \n",strerror(errno));
- exit(1);
- }
- while (1)
- {
- if( (rv = apr_socket_accept(&from,sock1,mp) ) != APR_SUCCESS )
- {
- fprintf(stderr,"accept socket fail: %d %s \n",rv,strerror(errno));
- continue;
- }
- apr_socket_send(from,sndbuf,plen);
- apr_socket_recv(from, rcvbuf, plen);
- rcvbuf[*plen] = '\0';
- printf("recv msg from client: %s\n, the recv len is %d\n", rcvbuf,*plen);
- }
- apr_socket_close(sock1);
- apr_pool_destroy(mp);
- apr_terminate();
- }
复制代码 下面是socket client:
- #define BUFLEN 30
- #define PORT 5671
- int main()
- {
- apr_status_t rv;
- apr_pool_t *mp;
- apr_socket_t *sock1 = NULL;
- const char *hostname = "127.0.0.1";
- apr_sockaddr_t *sa;
- apr_size_t len = 30;
- apr_size_t *plen = &len;
- char *bufdata;
-
- apr_initialize();
- apr_pool_create(&mp,NULL);
- bufdata = apr_palloc(mp,BUFLEN);
-
- if ( (rv = apr_sockaddr_info_get(&sa,hostname,APR_INET,PORT,0,mp)) != APR_SUCCESS )
- {
- fprintf(stderr,"get sockaddr info fail: %s\n",strerror(errno));
- exit(1);
- }
- if( (rv = apr_socket_create(&sock1,sa->family,SOCK_STREAM,APR_PROTO_TCP,mp) ) != APR_SUCCESS )
- {
- fprintf(stderr,"create socket fail: %s\n",strerror(errno));
- exit(1);
- }
- if( (rv = apr_socket_connect(sock1,sa)) !=APR_SUCCESS )
- {
- fprintf(stderr,"connect socket fail: %s\n",strerror(errno));
- exit(1);
- }
-
- printf("input the string: \n");
- fgets(bufdata,BUFLEN, stdin);
- apr_socket_send(sock1,bufdata,plen);
-
- apr_socket_recv(sock1, bufdata, plen);
- bufdata[*plen] = '\0';
- printf("recv msg from client: %s\n", bufdata);
- apr_socket_close(sock1);
- apr_pool_destroy(mp);
- apr_terminate();
- return 0;
- }
复制代码 头文件我没添加上去的。 |
|