显示从socket连接发送的十六进制

时间:2011-08-24 13:39:07

标签: objective-c cocoa

即时使用LXsocket作为我的网络提供商 我已经设置了一个服务器和客户端进行测试。我也有wirehark到位,看看发送的是什么 客户端:

    socket = [[LXSocket alloc] init];
        if ([socket connect: host port: port] == NO) 
        { 
            //cant connect!
            [socket release]; 
            NSLog(@"cannot create socket"); 
            return FALSE;
        }

        //connect hex string being sent
        const char connectByteArray[] = {
            0x01, 0x00, 0x07, 0x7f, 0x00, 0x00, 0x01, 0x00, 0x03, 0x40
        };

//send bytes    this works and the packets shown in wireshark reflect the byte array above
        [socket sendBytes:connectByteArray length:sizeof(connectByteArray)];

//receive bytes
        id *object = [socket readBytesWithLength:sizeof(connectByteArray)];

服务器:

LXSocket* serverSocket = [[LXSocket alloc] init];
    [serverSocket bindToPort: 1234];
    [serverSocket listen: 5];
    LXSocket *socket = [serverSocket accept];


    const char connectByteArray[] = {
        0x01, 0x00, 0x07, 0x7f, 0x00, 0x00, 0x01, 0x00, 0x03, 0x40
    };


    [socket sendBytes:connectByteArray length:sizeof(connectByteArray)];

我的问题是我无法让cocoa正确导出字节数组。我尝试过很多不同的格式标签而没有任何运气。我怎么能得到这个来记录正确的字节数组,即。 01:00:07:7f:00:00:01:00:03:40 ????

NSLog(@"return data %X",object);
     NSLog(@"return data %f",object);
     NSLog(@"return data %e",object);
     NSLog(@"return data %llu",object);
     NSLog(@"return data %hu",object);

2011-08-24 08:24:44.507 Chameleon [5574:207]返回数据4C053B0

2011-08-24 08:24:44.508 Chameleon [5574:207]返回数据0.000000

2011-08-24 08:24:44.509 Chameleon [5574:207]返回数据2.125934e-313

2011-08-24 08:24:44.510 Chameleon [5574:207]返回数据43029386160

2011-08-24 08:24:44.511 Chameleon [5574:207]返回数据21424

#import "LXSocket.h"
#import <sys/socket.h>
#import <sys/types.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <netdb.h>

@implementation LXSocket

+ (id)socket {
    return [[[LXSocket alloc] init] autorelease];
}

- (id)initWithCSocket:(SOCKET)_socket {
    if ((self = [super init])) {
        m_socket = _socket;
    }
    return self;
}

- (id)init {
    if ((self = [super init])) {
        m_socket = socket(AF_INET, SOCK_STREAM, 0);
    }
    return self;
}

- (BOOL)bindToPort:(unsigned)port {
    struct sockaddr_in service;
    service.sin_family = AF_INET;
    service.sin_addr.s_addr = INADDR_ANY;
    service.sin_port = htons(port);
    if (bind(m_socket, (struct sockaddr *) &service, sizeof(service)) == -1) {
        NSLog(@"bind() failed -- %s\n", strerror(errno));
        close(m_socket);
        return NO;
    } else return YES;
}

- (BOOL)listen:(unsigned)limit {
    if (listen(m_socket, limit) == -1) {
        printf("listen(): Error listening on socket\n");
        return NO;
    } else return YES;
}

- (LXSocket*)accept {
    SOCKET AcceptSocket;
    while (YES) {
        AcceptSocket = -1;
        while (AcceptSocket == -1) {
            AcceptSocket = accept(m_socket, NULL, NULL);
        }
        //printf("Server: Client Connected!\n");
        //m_socket = AcceptSocket; 
        return [[LXSocket alloc] initWithCSocket: AcceptSocket];
    }
    return nil;
}

- (BOOL)connect:(NSString*)host port:(unsigned)port {
    struct sockaddr_in clientService;
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr([host UTF8String]);
    clientService.sin_port = htons(port);
    if (connect(m_socket, (struct sockaddr *) &clientService, sizeof(clientService)) == -1) {
        printf("Client: connect() - Failed to connect.\n");
        return NO;
    } else return YES;
}

- (BOOL)sendBytes:(const void*)bytes length:(unsigned)len {
    int sent = send(m_socket, bytes, len, 0);
    return sent == len;
}

- (void*)readBytesWithLength:(unsigned)len {
    void* buffer = malloc(len);
    int received = recv(m_socket, buffer, len, 0);
    if (received <= 0) {
        free(buffer);
        return NULL;
    }
    if (received < len) {
        unsigned remaining = len;
        char* ptr = buffer;
        do {
            remaining -= received;
            ptr += received;
            received = recv(m_socket, ptr, remaining, 0);
            if (received <= 0) {
                free(buffer);
                return NULL;
            }
        } while (received < remaining);
    }
    return buffer;
}

- (BOOL)sendData:(NSData*)data {
    const void* ptr = [data bytes];
    BOOL succeeded = NO;
    if ([self sendInt: [data length]])
        if ([self sendBytes: ptr length: [data length]]) succeeded = YES;
    //free(ptr);
    return succeeded;
}

- (NSData*)readData{
    unsigned len = [self readInt];
    if (len > 0) {
        void* ptr = [self readBytesWithLength: len];
        if (ptr != NULL) {
            NSData* data = [NSData dataWithBytes: ptr length: len];
            free(ptr);
            return data;
        }
    }
    return nil;
}

- (BOOL)sendObject:(id)object {
    NSMutableData* data = [[NSMutableData alloc] init];
    NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData: data];
    [archiver encodeRootObject: object];
    [archiver finishEncoding];
    BOOL succeeded = [self sendData: data];
    [archiver release];
    [data release];
    return succeeded;
}

- (id)readObject {
    NSData* data = [self readData];
    if (data != nil) {
        NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData: data];
        id object = [[[unarchiver decodeObject] retain] autorelease];
        [unarchiver release];
        return object;
    }
    return nil;
}

- (BOOL)sendInt:(int)n {
    return [self sendBytes: &n length: sizeof(n)];
}

- (BOOL)sendDouble:(double)n {
    return [self sendBytes: &n length: sizeof(n)];
}

- (BOOL)sendInt64:(long long)n {
    return [self sendBytes: &n length: sizeof(n)];
}

- (int)readInt {
    void* buffer = [self readBytesWithLength: sizeof(int)];
    if (buffer == NULL) return 0;
    int n;
    memcpy(&n, buffer, sizeof(n));
    free(buffer);
    return n;
}

- (double)readDouble {
    void* buffer = [self readBytesWithLength: sizeof(double)];
    if (buffer == NULL) return 0;
    double n;
    memcpy(&n, buffer, sizeof(n));
    free(buffer);
    return n;
}

- (long long)readInt64 {
    void* buffer = [self readBytesWithLength: sizeof(long long)];
    if (buffer == NULL) return 0;
    long long n;
    memcpy(&n, buffer, sizeof(n));
    free(buffer);
    return n;
}

- (BOOL)sendShort:(short)n {
    return [self sendBytes: &n length: sizeof(n)];
}

- (short)readShort {
    void* buffer = [self readBytesWithLength: sizeof(short)];
    if (buffer == NULL) return 0;
    short n;
    memcpy(&n, buffer, sizeof(n));
    free(buffer);
    return n;
}

- (BOOL)sendLong:(long)n {
    return [self sendBytes: &n length: sizeof(n)];
}

- (BOOL)sendUnsingedLongLong:(unsigned long long)n {
    return YES;//return [self sendBytes: &n length: sizeof(n)];
}

- (long)readLong {
    void* buffer = [self readBytesWithLength: sizeof(long)];
    if (buffer == NULL) return 0;
    long n;
    memcpy(&n, buffer, sizeof(n));
    free(buffer);
    return n;
}

- (void)sendString:(NSString*)string {
    const char* s = [string UTF8String];
    int len = strlen(s);
    [self sendInt: len];
    [self sendBytes: s length: len + 1];
}

- (NSString*)readString {
    int len = [self readInt];
    char* s = [self readBytesWithLength: len + 1];
    NSString* string = [NSString stringWithUTF8String: s];
    free(s);
    return string;
}

- (NSString*)resolveHostName:(NSString*)hostName {
    struct hostent* host = gethostbyname([hostName UTF8String]);
    if (host == NULL) {
        printf("Error resolving host name: %d\n", strerror(errno));
        return nil;
    } else {
        struct in_addr* addr = (struct in_addr*) host->h_addr_list[0];
        char* ip = inet_ntoa(*addr);
        return [NSString stringWithUTF8String: ip];
    }
}

- (void)dealloc {
    close(m_socket);
    [super dealloc];
}

@end

进一步的结果(记住传递的原始十六进制字符串是0x01,0x00,0x07,0x7f,0x00,0x00,0x01,0x00,0x03,0x40)(0100077f000001000340):

   id *object = [socket readBytesWithLength:10];
    NSLog(@"return data %X",*object);   =  return data 7F070001
   NSLog(@"return data %llu",*object);  =  return data 45080838145


   double object = [socket readInt64];
    NSLog(@"return data %X",*object);   =  return data F0700010
    NSLog(@"return data %llu",*object); = return data 4823355235012444176 (hex: 0x42F00007F0700010)

1 个答案:

答案 0 :(得分:1)

你可能需要编写一个特殊的函数来以这种方式打印,因为你需要遍历字符:

- (NSString *)bytesToString:(char *)bytes length:(int)length {
    // Each byte is 2 hex characters, plus we need a ':' between each byte
    NSMutableString *result = [NSMutableString stringWithCapacity:2*length + length - 1];

    for (int i = 0; i < length; i++) {
        if (i < length - 1) {
            [result appendFormat:@"%02X:", bytes[i]];
        }
        else {
            [result appendFormat:@"%02X", bytes[i]];
        }
    }

    return result; // Result is auto-released
}

定义此功能后,您应该能够按如下方式记录:

NSLog(@"return data %@",[self bytesToString:object length:sizeof(connectByteArray)]);