1 /* 2 * Copyright 2006, Haiku, Inc. All Rights Reserved. 3 * Distributed under the terms of the MIT License. 4 */ 5 #ifndef NET_UTILITIES_H 6 #define NET_UTILITIES_H 7 8 9 #include <net_buffer.h> 10 #include <net_datalink.h> 11 12 #include <stdlib.h> 13 14 class Checksum { 15 public: 16 struct BufferHelper { 17 BufferHelper(net_buffer *_buffer, net_buffer_module_info *_bufferModule) 18 : buffer(_buffer), 19 bufferModule(_bufferModule) 20 { 21 } 22 net_buffer *buffer; 23 net_buffer_module_info *bufferModule; 24 }; 25 26 Checksum(); 27 28 Checksum& operator<<(uint8 val); 29 Checksum& operator<<(uint16 val); 30 Checksum& operator<<(uint32 val); 31 Checksum& operator<<(const BufferHelper &bufferHelper); 32 33 operator uint16(); 34 35 private: 36 uint32 fSum; 37 }; 38 39 inline Checksum::Checksum() 40 : fSum(0) 41 { 42 } 43 44 inline Checksum& Checksum::operator<<(uint8 _val) { 45 #if B_HOST_IS_LENDIAN 46 fSum += _val; 47 #else 48 uint16 val = _val; 49 fSum += val << 8; 50 #endif 51 return *this; 52 } 53 54 inline Checksum& Checksum::operator<<(uint16 val) { 55 fSum += val; 56 return *this; 57 } 58 59 inline Checksum& Checksum::operator<<(uint32 val) { 60 fSum += (val & 0xFFFF) + (val >> 16); 61 return *this; 62 } 63 64 inline Checksum& Checksum::operator<<(const BufferHelper &bufferHelper) { 65 net_buffer *buffer = bufferHelper.buffer; 66 fSum += bufferHelper.bufferModule->checksum(buffer, 0, buffer->size, false); 67 return *this; 68 } 69 70 inline Checksum::operator uint16() { 71 while (fSum >> 16) { 72 fSum = (fSum & 0xffff) + (fSum >> 16); 73 } 74 uint16 result = (uint16)fSum; 75 result ^= 0xFFFF; 76 return result; 77 } 78 79 80 // helper class that prints an address (and optionally a port) into a buffer that 81 // is automatically freed at end of scope: 82 class AddressString { 83 public: 84 inline AddressString(net_domain *domain, const sockaddr *address, 85 bool printPort = false) 86 : fBuffer(NULL) 87 { 88 domain->address_module->print_address(address, &fBuffer, printPort); 89 } 90 91 inline AddressString(net_domain *domain, const sockaddr &address, 92 bool printPort = false) 93 : fBuffer(NULL) 94 { 95 domain->address_module->print_address(&address, &fBuffer, printPort); 96 } 97 98 inline ~AddressString() 99 { 100 free(fBuffer); 101 } 102 103 inline char *Data() 104 { 105 return fBuffer; 106 } 107 private: 108 char *fBuffer; 109 }; 110 111 #endif // NET_UTILITIES_H 112