Android examples for java.nio:ByteBuffer
Performs an IP checksum (used in IP header and across UDP payload) on the specified portion of a ByteBuffer
/*//ww w. j a v a 2s . co m * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.system.OsConstants; import android.system.OsConstants; import java.net.Inet6Address; import java.net.InetAddress; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.ShortBuffer; public class Main{ /** * Performs an IP checksum (used in IP header and across UDP * payload) on the specified portion of a ByteBuffer. The seed * allows the checksum to commence with a specified value. */ private static int checksum(ByteBuffer buf, int seed, int start, int end) { int sum = seed; final int bufPosition = buf.position(); // set position of original ByteBuffer, so that the ShortBuffer // will be correctly initialized buf.position(start); ShortBuffer shortBuf = buf.asShortBuffer(); // re-set ByteBuffer position buf.position(bufPosition); final int numShorts = (end - start) / 2; for (int i = 0; i < numShorts; i++) { sum += intAbs(shortBuf.get(i)); } start += numShorts * 2; // see if a singleton byte remains if (end != start) { short b = buf.get(start); // make it unsigned if (b < 0) { b += 256; } sum += b * 256; } sum = ((sum >> 16) & 0xFFFF) + (sum & 0xFFFF); sum = ((sum + ((sum >> 16) & 0xFFFF)) & 0xFFFF); int negated = ~sum; return intAbs((short) negated); } }