InternetClient
#include
#include <sys/types.h>#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
int main()
{
int sd,len; struct sockaddr_in address;
int res; char c[100]=“Hello server!”; sd=socket(AF_INET,SOCK_STREAM,0); address.sin_family=AF_INET; address.sin_port=htons(0x6400); address.sin_addr.s_addr=inet_addr(“192.168.3.7”); len=sizeof(address);
res=connect(sd,(struct sockaddr*)&address,len); if(res==-1)
{ perror(“error\n”); return 0; } while(1) {
sleep(1);
write(sd,c,sizeof©);
read(sd,c,100); cout<<“received:”<<c<<endl; }
close(sd);
return 0;}
InternetServer
#include
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;void a(void arg);
int main(){
int sd,cd;
int ret;
pthread_t thread; sd=socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in server_address; server_address.sin_family=AF_INET; server_address.sin_port=htons(0x6400); server_address.sin_addr.s_addr=inet_addr(“192.168.3.2”); int res=bind(sd,(struct sockaddr)&server_address,sizeof(server_address)); if(res<0) {
cout<<“error number:”<<errno<<endl;
return 0;
}
listen(sd,5);
struct sockaddr_in client_address; socklen_t client_len=sizeof(client_address);
while(1) {
cd=accept(sd,(struct sockaddr)&client_address,&client_len); ret=pthread_create(&thread,0,a,(void*)&cd); if(ret==-1) {
perror(“failed creating thread\n”); continue; } }}
void * a(void arg){ int cd=(int*)arg;
while(1) {
char c[100];
read(cd,c,100);
cout<<“received:”<<c<<endl;
strcpy(c,“Hello client!”); write(cd,c,sizeof©); }
close(cd)];}