linux下TCP socket编程初步(1)

 Socket编程:

结构:sockaddr_in

Sin_family 地址家族 AF_INET AF_INET6

Sin_port 16位

Sin_addr s_addr 32位

 

Server:socket,bind,listen,accept

Client:socket,connect

另外,今天刚看到一篇博客中写的比较清楚,可以参考:

http://blog.csdn.net/kikilizhm/article/details/7858405

服务端程序:
//ipserver.cc
#include<iostream>
using namespace std;
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<fcntl.h>
#include<string>
#include<stdlib.h>

int main(int argc,char* argv[])
{
	short port=12345;
	if(argc>1)
		port=atoi(argv[1]);
	int ss=socket(AF_INET,SOCK_STREAM,0);
	if(ss<0)
		return -1;
	sockaddr_in si;
	si.sin_family=AF_INET;
	si.sin_port=htons(port);
	si.sin_addr.s_addr=0;//INADDR_ANY 不管哪个IP地址
	socklen_t len=sizeof(si);	
	int r=bind(ss,(sockaddr*)&si,len);
	if(r<0)
		return -1;
	r=listen(ss,20);
	if(r<0)
		return -1;
	sockaddr_in c;
	for(;;)
	{
		len=sizeof(c);
		int cs=accept(ss,(sockaddr*)&c,&len);//对方套接地址放第二个参数
		if(cs<0)
			continue;		
		char ip[100];//#include<arpa/inet.h>
		inet_ntop(AF_INET,&c.sin_addr.s_addr,ip,sizeof(ip));
		cout<<	ip<<"到此访问"<<endl;
		string msg="your ip:";
		msg+=ip;
		msg+='\n';
		write(cs,msg.c_str(),msg.size());
		close(cs);
	}
}


 

编译后,执行./a.out 12345

程序在等待,这时在windows下telnet:(客户端)

telnet 10.31.50.149 12345

也可以自己写一客户端程序:

//ipclient.cc
#include<iostream>
using namespace std;
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<fcntl.h>
//#include<string>
#include<stdlib.h>

int main(int argc,char* argv[])
{
	if(argc!=3)
	{
		cout<<*argv<<"ip port"<<endl;
		return 0;	
	}
	int s=socket(AF_INET,SOCK_STREAM,0);
	if(s<0)
		return -1;
	sockaddr_in si;
	short port=atoi(argv[2]);
	char* ip=argv[1];
	si.sin_family=AF_INET;
	si.sin_port=htons(port);
	inet_pton(AF_INET,ip,&si.sin_addr.s_addr);
	int r=connect(s,(sockaddr*)&si,sizeof(si));
	if(r<0)
		return -1;
	char msg[200];
	int n=read(s,msg,sizeof(msg));
	if(n<0)
		return -1;
	msg[n]='\0';
	cout<<msg<<endl;
	close(s); 
	return 0;
}

分别编译通过:

客户端:

./ipc 127.0.0.1 12345

your ip:127.0.0.1

服务器端:

./ips 12345

127.0.0.1到处访问

 

你可能感兴趣的:(编程,linux,windows,socket,Stream,tcp)