星期五, 9月 26, 2008

Client 端,簡單開socket 方式

Client 端,簡單開socket 方式
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int sock_connect(int *fd, char *ip, int port){
        struct  sockaddr_in     addr;

        *fd = socket(PF_INET, SOCK_STREAM, 0);

        memset(&addr, 0, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons( port );

        inet_aton( (const char*)ip, &addr.sin_addr);

        if( connect( *fd, (struct sockaddr*)&addr, sizeof(addr)) != EXIT_SUCCESS ){
                fprintf(stderr,"Connect Failure===\n");
                return EXIT_FAILURE;
        }
        printf("fd=%d success\n", *fd );
        return EXIT_SUCCESS;
}


int main(int argc, char **argv){
        int fd, ret;
        char buf[256];

        sock_connect(&fd, "domain", 25 );

        ret = write ( fd, argv[1], strlen( argv[1] ) );
        printf("Send msg=%s len=%d ret=%d\n", argv[1], strlen( argv[1] ) , ret );
        ret = read( fd, buf, 256 );

        printf("buf=%s len=%d\n", buf, ret );

        close( fd );
}

沒有留言: